Reputation: 11
Been trying for over 4 hours now, I'm no expert in the slightest I definitely need help with this. Any idea what is going wrong?
// Declare variables
int inches = 0;
double centimetres = 0;
string input;
//Ask for input
Console.Write("Enter Number of centimetres to be converted: ");
input = Console.ReadLine();
//Convert string to int
centimetres = double.Parse(input);
inches = int.Parse(input);
inches = int.Parse(centimetres / 2.54);
//Output result
Console.WriteLine("Inches = " + inches + "inches.");
}
}
Upvotes: 1
Views: 2014
Reputation: 31
The problem is most like this line: inches = int.Parse(centimetres / 2.54);
int.Parse takes a string and centimetres / 2.54 is a double. to convert a double to an int use Convert.ToInt32 instead.
Upvotes: 1
Reputation: 63105
the result of centimetres / 2.54
is double, there is nor overload accept double as parameter in int.Parse
Upvotes: 0
Reputation: 174397
The "conversion" inches = int.Parse(centimetres / 2.54);
makes no sense. int.Parse
is used to transform a string
that represents a number into an int
. But you pass it a double
.
To make it work, your code would need to look like this:
//Ask for input
Console.Write("Enter Number of centimetres to be converted: ");
double input = Console.ReadLine();
//Convert string to int
double centimetres = double.Parse(input);
double inches = centimetres / 2.54;
//Output result
Console.WriteLine("Inches = " + inches + "inches.");
Some points:
inches = int.Parse(input);
completely, because the result is never used as it is overwritten in the very next line.inches
as double
not as int
. Otherwise you would be unable to have fractional inches.inches
. There is no need for parsing here.Upvotes: 1