settingsAccountsettings
Menusettings

Q: How to sum 3 real numbers (not only integers) in C# and print them

+5 votes

I need to write a program that reads 3 real numbers (not only integers) from the console and prints their sum in C#.

Examples:

a

b

c

sum

3

4

11

18

-2

0

3

1

5.5

4.5

20.1

30.1

 

asked in C# category by user john7

3 Answers

+1 vote

The main thing you should do is to first parse (or convert) the strings to integers (in this case doubles) because Console.ReadLine(); reads only string values.

Here's the code:

using System;

class SumOfThreeNumbers
{
    static void Main()
    {
        Console.Write("Please write your first number: ");
        string numberOne = Console.ReadLine();
        double numberOneP = double.Parse(numberOne);

        Console.Write("Please write your second number: ");
        string numberTwo = Console.ReadLine();
        double numberTwoP = double.Parse(numberTwo);

        Console.Write("Please write your third number: ");
        string numberThree = Console.ReadLine();
        double numberThreeP = double.Parse(numberThree);
        Console.WriteLine("The sum of the three numbers is: " + (numberOneP+numberTwoP+numberThreeP));

    }
}
answered by user samfred5830
edited by user golearnweb
+1 vote

Or this one:

using System;

class Sum
{
    static void Main()
    {
        Console.Write("Enter your first number: ");
        double firstNumber = double.Parse(Console.ReadLine());
        Console.Write("Enter your second number: ");
        double secondNumber = double.Parse(Console.ReadLine());
        Console.Write("Enter your third number: ");
        double thirdNumber = double.Parse(Console.ReadLine());

        Console.WriteLine("Sum of these numbers is " + (firstNumber + secondNumber + thirdNumber));

    }
}


 

answered by user paulcabalit
edited by user golearnweb
+1 vote

Or this solution (decimal instead of double - as it includes bigger range of numbers):

using System;

namespace ConsoleInputOutput
{
    public static class SumOfThree
    {
        public static void Main()
        {
            decimal a = decimal.Parse(Console.ReadLine());
            decimal b = decimal.Parse(Console.ReadLine());
            decimal c = decimal.Parse(Console.ReadLine());
            Console.WriteLine(a + b + c);
        }
    }
}

 

answered by user richard8502
edited by user golearnweb
...