SweetNostrils SweetNostrils - 2 months ago 9
C# Question

My code in C# for a simple currency conversion program won't work properly for me

The code is just an exercise for college to convert Euros to Dollars but I just can't figure out why it won't work. I've included the code here. I added in an extra Console.ReadLine(); myself so that I could find out what the answer was. This is because if I only have the one, the program just starts and then finishes in a flash. The answer always seems to be 54.88.
Any help would be greatly appreciated.

EDIT: I accidentally put "Enter Dollars" instead of "Enter Euros." This shouldn't have affected the code, just the wording. Garbage in, Garbage out is what happened to me possibly though.

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

namespace euro_to_dollar
{
class Program
{
static void Main(string[] args)
{
float dollars, conversion_rate, euros;
conversion_rate = 1.12f;
Console.WriteLine("Enter in Dollars:");
dollars = Console.Read();
euros = dollars * conversion_rate;
Console.WriteLine("Dollars:" + euros);
Console.ReadLine();
Console.ReadLine();
}
}
}

Answer

Console.Read only reads one character from the console.

Instead the code should use dollars = float.Parse(Console.ReadLine());

So the complete code would be:

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

namespace euro_to_dollar
{
    class Program
    {
        static void Main(string[] args)
        {
            float dollars, conversion_rate, euros;
            conversion_rate = 1.12f;
            Console.WriteLine("Enter in Dollars:");
            dollars = float.Parse(Console.ReadLine());
            euros = dollars * conversion_rate;
            Console.WriteLine("Dollars:" + euros);
            Console.ReadLine();
            Console.ReadLine();
        }
    }
}

Edit: The reason you were getting 54.88 every time is because every time you tested a number, it started with the character 1, which is represented with the number 49 in ASCII. Thus, 1.12 * 49 = 54.88

Comments