【问题标题】:C# float and decimal input and mathC#浮点和十进制输入和数学
【发布时间】:2012-08-26 05:20:13
【问题描述】:

用户输入他们的年龄,我必须返回该年龄,然后以十进制值返回年龄数字的一半,并以美元金额显示输入的工资。

给我的样本变量包括:

    float y;

以下是我在编写的代码中如何使用它的示例:

    using System;

    public class Profile
    {
        static void Main(string[] args)
        {
            int x;
            float y = 2.0f;
            var result = x / y;

            Console.Write("Please enter your age:");
            x = Covert.ToInt32(Console.ReadLine());

            Console.WriteLine("Your age is {0}, and half your age is {1}."
            , x, result);

            Console.ReadKey();
        }
    }

但如果我输入“18”这样的数字,它会显示“你的年龄是 18 岁,你的一半年龄是 9 岁”。我无法让它给我“9.0”之类的东西。

我还看到我的应用程序应该用小数点和逗号来说明工资(例如 $250,000.00),但它只显示“$250000”。我使用的一个例子是:

    decimal z;

    Console.Write("Please enter your salary");
    z = Convert.ToDecimal(Console.ReadLine());

    Console.WriteLine("Your salary is {0}.", z);

    Console.ReadKey();

我只是不应该在结果中看到小数吗?

【问题讨论】:

    标签: c# math floating-point decimal user-input


    【解决方案1】:

    使用字符串格式选项:

    Console.WriteLine("Your age is {0}, and half your age is {1:00.00}."
            , x, result);
    

    【讨论】:

    • 这成功了!另外,我发现了有关使用字符串格式选项的信息。我假设: Console.WriteLine("${1:.00}", x) 将与: Console.WriteLine("{1:C}", x) 相同
    • 我的声望太低,现在无法给你投票,但我选择了你的答案作为正确的答案。谢谢你:)
    【解决方案2】:

    您需要在收到用户输入后执行数学运算。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多