Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Wrong Value stored in variable

Tags:

c#

console

I am fairly new to programming so have some mercy ;) I am trying to build a program that can solve equations and give gradient and so on in c#, so I can make it more complex gradually. Problem is, there appears to be a wrong value from my input when I tried to start building it.

Console: Given value for "a": 9 The Output: 57

My Code:

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Input an linear Eqasion in the following Pattern -- a * x + b");
            Console.Write("Given value for \"a\":");
            decimal aValue;
            aValue = Console.Read();
            Console.Write(aValue);
        }
    }
}
like image 912
Vale Avatar asked Nov 29 '25 16:11

Vale


2 Answers

Console.Read() returns an int, but not in the way you think. It returns the numeric value of the typed character, not the human-intuitive interpretation of a character that coincidentally happens to be a number. Consider for example what it would return if you type a letter, or any other non-numeric character.

And what is the numeric (decimal) value for the character '9'? 57 is.

It sounds like you want to read the line, not the character. For example:

string aValue;
aValue = Console.ReadLine();
Console.Write(aValue);

Remember that you'll need to press return to send the line to the application.

If you'll later need the value to be numeric, you'll still want to input the string but will want to parse it. For example:

string aValue;
aValue = Console.ReadLine();
if (decimal.TryParse(aValue, out decimal numericValue)
{
    Console.Write(numericValue);
}
else
{
    // The value could not be parsed as a decimal, handle this case as needed
}
like image 125
David Avatar answered Dec 02 '25 05:12

David


Console.Read returns the character code entered on the command line in this scenario. The ASCII character code of 9 is 57. If you're wanting numeric input, you'd be better using Console.ReadLine with Decimal.Parse (or better yet, Decimal.TryParse)

It is also worth noting that Console.Read only returns one character at a time, meaning for any inputs past 1 digit you'll need special handling. I highly recommend using ReadLine and parsing the string over handling converting the character codes to the number they represent.

like image 20
Zaelin Goodman Avatar answered Dec 02 '25 05:12

Zaelin Goodman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!