C#控制台程序写一个计算器 [英] C#console program writes a calculator
本文介绍了C#控制台程序写一个计算器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
控制台程序写入acalculator以满足加法和减法乘法
我尝试过:
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;打破;
case/:float y = m / n;打破;
case+:float z = m + n;打破;
case - :float w = m - n;打破;
case%:float q = m%n;打破;
}
//Console.Write();
解决方案
不,那不行。
看看你的代码,很明显它不对:哪一个switch语句将被执行?没有 - 因为k
总是一个空字符串。
对于初学者,不要使用float.parse
转换数字:使用float.TryParse
或更好,使用double.TryParse
而不是。我建议的是写一个方法来返回一个数字:
private static double GetNumber( string prompt)
{
double 结果;
do
{
Console.WriteLine(prompt);
string inp = Console.ReadLine();
if ( double .TryParse(inp, out 结果))
{
break ;
}
Console.WriteLine( 对不起,这不是有效的请再试一次。);
} while ( true );
返回结果;
}然后你可以调用两次以获取两个操作数。
然后使用Console.ReadLine获取操作符,并对用户执行switch语句输入
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("");
解决方案
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 - becausek
is always an empty string.
For starters, don't usefloat.parse
to convert numbers: usefloat.TryParse
or better, usedouble.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.
这篇关于C#控制台程序写一个计算器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文