Home > Mobile >  issue while calculating average price in c#
issue while calculating average price in c#

Time:04-17

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();
        }
    }
}

When I input the first buying price, I want to enter the amount in decimal like 10.20, while for the second buying price 20.20, then I should compute the average price and print it, but when I run the code it throws an error.

Can you help me?

CodePudding user response:

When dealing with money is always a good practice to use decimal, you could use float or double, but you could end with a rounding issue.

The problem in your code is that you were trying to use an int variable to store a decimal entry, so a conversion exception was being thrown.

Your code should looks like this:

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();
}

CodePudding user response:

You try to parse string, that contains floating-point value into integer one.

Possible solutions:

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 
}
  • Related