c# - 在 C# 中将字符串/整数转换为 double

标签 c# int double

这里有一个简单的计算器,用来计算将公斤价格除以您分配给糖果的钱可以得到多少糖果。

例如:“糖果每公斤 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 ,即没有小数点的“整数”,例如 142。一旦您想使用小数,您就需要一个可以支持它的变量类型。

C# 内置了一些:floatdoubledecimal。如果您处理的是货币数据,其中精度和准确度非常重要,您必须使用 decimal

您还想使用返回 boolTryParse() 而不是抛出异常的 Parse() 方法。

因此请更改您的代码以使用 decimaldecimal.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/

相关文章:

c# - 在 C# 中,使用完全限定名称与 'using' 指令相比性能更高吗?

c# - 在 "friend"程序集中隐藏内部接口(interface)

c# - 为什么 Request.BodyReader 是空的,当我添加请求参数时(ASP.NET Core 3.0)

mysql - 在mysql中转换为十进制

c++ - 将 unsigned char 转换为 int 和 short

c# - 在 C# 中将 double 转换为十六进制

c# - 通过 C#(VSTO)/VBA 访问 Excel 2010 公式编辑器

java - 双减 int 给出意想不到的结果

.net - 为什么 Assert.AreEqual(1.0, double.NaN, 1.0) 通过?

c - Scanf for double 在 Dev C++ 中不起作用