Click here to Skip to main content
13,740,333 members
Rate this:
 
Please Sign up or sign in to vote.
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 10-Nov-17 4:18am
Updated 10-Nov-17 4:30am

1 solution

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

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:
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.
  Permalink  
v2
Comments
Karthik Bangalore 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)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Cookies | Terms of Service
Web01-2016 | 2.8.180920.1 | Last Updated 11 Nov 2017
Copyright © CodeProject, 1999-2018
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100