繁体   English   中英

在 c# 中计算平均价格时出现问题

[英]issue while calculating average price in c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace average_stock_calculator
{
    class Program
    {
        static void Main(string[] args)
        {
            double  a, b, sum, average;

            Console.WriteLine("First purchase price:");
            a = Convert.ToInt64(Console.ReadLine());
            
            Console.WriteLine("Second purchase price:");
            b = Convert.ToInt64(Console.ReadLine());

            //Processing
            sum = a + b;
            average = sum/2;
            
            Console.WriteLine("Average buying price={0}", average);

            Console.ReadKey();
        }
    }
}

当我输入第一个购买价格时,我想输入小数形式的金额,如10.20 ,而对于第二个购买价格20.20 ,我应该计算平均价格并打印出来,但是当我运行代码时它会抛出错误。

你能帮助我吗?

处理金钱始终是使用decimal的好习惯,您可以使用floatdouble ,但最后可能会出现舍入问题。

您的代码中的问题是您试图使用int变量来存储decimal条目,因此抛出了转换异常。

您的代码应如下所示:

static void Main(string[] args)
{
    decimal a, b, sum, average;

    Console.WriteLine("First purchase price:");
    a = Convert.ToDecimal(Console.ReadLine());

    Console.WriteLine("Second purchase price:");
    b = Convert.ToDecimal(Console.ReadLine());

    //Processing
    sum = a + b;
    average = sum / 2m;

    Console.WriteLine("Average buying price={0}", average);

    Console.ReadKey();
}

您尝试将包含浮点值的字符串解析为 integer 之一。

可能的解决方案:

var x = Convert.ToDouble(input);
var x = Convert.ToDecimal(input);
var x = double.Parse(input);
var x = decimal.Parse(input);
if (double.TryParse(input, out var x)) 
{
    // do smth with x 
}
if (decimal.TryParse(input, out var x)) 
{
    // do smth with x 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM