C# doubling value alone

Asked

Viewed 79 times

-1

I’m appending C#, but the code below doubles the value and terminates unexpectedly. Can anyone take a look?

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

namespace ConsoleApp5
{
    class Program
    {
        static void Main(string[] args)
        {
            float a, b = 0;
            float resul = 0;
            string dado;


            Console.WriteLine("digite o primeiro valor");
            dado = Console.ReadLine();
            a = float.Parse(dado);
            Console.WriteLine("Digite o segundo valor");
            b = float.Parse(dado);
            resul = a + b;

            if (resul > 10)
            {
                Console.WriteLine(resul);

            }
            else 
            {
                Console.WriteLine("O valor" + resul,"é muito abaixo do esperado");

            }

            Console.WriteLine("encerre esse programa digitando qualquer tecla");
                Console.ReadLine();



        }
    }
}
  • Lacked a Console.ReadLine(); to read the second value

3 answers

1

In the code

Console.WriteLine("Digite o segundo valor");
            b = float.Parse(dado);

You are parsing the data without reading the console data. then when you do A + B, B is the same value as A, so it’s doubling A in the result.

The unexpected closure is due to the code

 else 
            {
                Console.WriteLine("O valor" + resul,"é muito abaixo do esperado");

            }

In this section we missed the + to concatenate the result variable with the text.

0


As mentioned in the comment, we failed to add the following line before assigning the value to the variable b

dado = Console.ReadLine();
b = float.Parse(dado);
...

0

First of all, variables must be initialized. However, the code can be simplified both for better understanding and for reading the code itself. Note below the code with the change and compare with your.

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

 namespace ConsoleApp5
 {
   class Program
   {
    static void Main(string[] args)
    { 
        decimal a = 0; 
        decimal b = 0;
        decimal resul = 0;  

        Console.WriteLine("digite o primeiro valor");
        a = decimal.Parse(Console.ReadLine());
        Console.WriteLine("Digite o segundo valor");
        b = decimal.Parse(Console.ReadLine());

        resul = a + b;

        if (resul > 10)
        {
            Console.WriteLine(resul);
        }
        else 
        {
            Console.WriteLine("O valor " + resul + " é muito abaixo do esperado");
        }

        Console.WriteLine("encerre esse programa digitando qualquer tecla...");
        Console.ReadLine();
    }
   }
 }

Now yes, it will work perfectly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.