簡體   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