【发布时间】:2015-11-18 12:42:18
【问题描述】:
这是一个简单的计算器,用来计算将公斤价格除以你分配给糖果的钱,你能得到多少糖果。
例如:“糖果每公斤 5 美元。我为糖果分配了 3.50 美元。我会使用这个程序来计算我得到的糖果数量。”
在使用小数之前它可以正常工作。我想将字符串转换为 Double 以便我可以在计算器中使用小数。 4 美元的价格和 8 美元的钱当然会产生 2 公斤的糖果。但是如果公斤价格是 4.80 美元而我有 9.30 美元的钱,我只会得到一个错误并导致命令提示符崩溃。
static void Main(string[] args)
{
//The variables
int int1;
int int2;
string text1;
string text2;
//The actual calculation
System.Console.Write("Please input the kilogram price of candy: ");
text1 = System.Console.ReadLine();
int1 = int.Parse(text1);
System.Console.Write("Please input the money allocated for candy ");
text2 = System.Console.ReadLine();
int2 = int.Parse(text2);
System.Console.WriteLine("With the amount of money you input you would get " + (int2 / int1) + " kilos of candy.");
}
}
}
【问题讨论】:
-
简单地使用Double.Parse?! (虽然我建议使用 .TryParse)
-
使用
Double.TryParse(text1, out myDoubleVariable);而不是使用整数。根据定义,整数是整数。 -
为什么
int不是double?附言。int1是一个糟糕的变量名:p -
您的问题是“为什么我不能将
4.80存储在int中”?也许您需要了解various numeric variable types C# offers。 -
另外,你没有甚至提供你的错误信息。请阅读FAQ 和How to Ask 几次..