Click here to Skip to main content
15,868,141 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
The console program writes acalculator to satisfy addition and subtraction multiplication

What I have tried:

    Console.Write("请输入数A");
    float n = float.Parse(Console.ReadLine());
    Console.WriteLine();
   // Console.Write("请选择符号(+,-,*,/,%):");

    Console.WriteLine();
    Console.Write("请输入数B");
    float m = float.Parse(Console.ReadLine());
    string k = "";
switch (k)
{
    case "*": float x = m * n; break;
    case "/": float y = m / n; break;
    case "+": float z = m + n; break;
    case "-": float w = m - n; break;
    case "%": float q = m % n; break;
}
            //Console.Write("");
Posted
Updated 10-Nov-17 4:30am

1 solution

No, that won't work.
Look at your code, and it's obvious that its isn't right: which one of the switch statements is going to be executed? None of them - because k is always an empty string.

For starters, don't use float.parse to convert numbers: use float.TryParse or better, use double.TryParse instead. And what I'd suggest is writing a method to return a number:
C#
private static double GetNumber(string prompt)
   {
   double result;
   do
      {
      Console.WriteLine(prompt);
      string inp = Console.ReadLine();
      if (double.TryParse(inp, out result))
         {
         break;
         }
      Console.WriteLine("I'm sorry, but that wasn't a valid number. Please try again.");
      } while (true);
   return result;
   }
You can then call that twice to fetch the two operands.
Then use Console.ReadLine to fetch the operator, and execute the switch statement on the user input.
 
Share this answer
 
v2
Comments
Karthik_Mahalingam 10-Nov-17 12:28pm    
5
George Swan 11-Nov-17 7:34am    
shouldn't that be
Console.WriteLine
OriginalGriff 11-Nov-17 7:40am    
What! You want me to find the SHIFT key *twice* in the same word? :laugh:

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900