[英]C# console application - commission calculator - how to pass variables into Main()
[英]C# Calculator Variables not reseting
計算器將運行並繼續進行相同的計算,直到您鍵入 stop 然后它將開始新的計算,但 num1 將保持上次計算中的最后一個值並且不會重置。
例子:
輸入數字 22
您要執行什么計算 +
輸入數字 33
答案 55
您要執行什么計算 /
輸入數字 5
答案 11
您要執行什么計算停止
輸入數字 2
您要執行什么計算 +
輸入數字 9
答案 20
Boolean x;
x = true;
while (x == true)
{
double num1;
double ans;
double num2;
string cal;
Boolean y;
y = true;
Console.WriteLine("Enter a number ");
num1 = Convert.ToInt32(Console.ReadLine());
while (y == true)
{
Console.WriteLine("What calculation do you want to perform ");
cal = Console.ReadLine();
Console.WriteLine("Enter a number ");
num2 = Convert.ToInt32(Console.ReadLine());
switch (cal)
{
case "+":
ans = add(num1, num2);
Console.WriteLine("Answer " + ans);
num1 = ans;
break;
case "-":
ans = sub(num1, num2);
Console.WriteLine("Answer " + ans);
num1 = ans;
break;
case "/":
ans = div(num1, num2);
Console.WriteLine("Answer " + ans);
num1 = ans;
break;
case "*":
ans = mul(num1, num2);
Console.WriteLine("Answer " + ans);
num1 = ans;
break;
case "Stop":
y = false;
break;
}
}
}
}
private static double add(double firstnumber, double secondnumber)
{
double answer;
answer = firstnumber + secondnumber;
return answer;
}
private static double sub(double firstnumber, double secondnumber)
{
double answer;
answer = firstnumber - secondnumber;
return answer;
}
private static double div(double firstnumber, double secondnumber)
{
double answer;
answer = firstnumber / secondnumber;
return answer;
}
private static double mul(double firstnumber, double secondnumber)
{
double answer;
answer = firstnumber * secondnumber;
return answer;
}
把它歸零
case "Stop":
y = false;
num1=0;
break;
該程序需要"Stop"
作為cal
的輸入以終止,但您輸入了"stop"
。 看到不同?
最好將輸入轉換為小寫
cal = Console.ReadLine().ToLower();
然后在 switch 語句中檢查它。 還要始終在 switch 中包含一個default
分支,因為您需要預料到意外情況。
switch (cal)
{
..
case "stop":
y = false;
break;
default:
// what happens if input is not +-*/ or stop?
break;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.