这里有一个简单的计算器,用来计算将公斤价格除以您分配给糖果的钱可以得到多少糖果。
例如:“糖果每公斤 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.");
}
}
最佳答案
您正在使用 int
变量类型,它只能包含 integer numbers ,即没有小数点的“整数”,例如 1
和 42
。一旦您想使用小数,您就需要一个可以支持它的变量类型。
C# 内置了一些:float
、double
和 decimal
。如果您处理的是货币数据,其中精度和准确度非常重要,您必须使用 decimal
。
您还想使用返回 bool
的 TryParse()
而不是抛出异常的 Parse()
方法。
因此请更改您的代码以使用 decimal
和 decimal.TryParse()
:
decimal pricePerKilogram;
string input = Console.ReadLine();
if (!decimal.TryParse(input, out pricePerKilogram))
{
// show error or retry
}
关于c# - 在 C# 中将字符串/整数转换为 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33780406/