3
votes

I'm having a trouble trying to fix a simple c# code. Here's the code:

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

namespace MoonGravity
{
    class MoonGravity
    {
        static void Main(string[] args)
        {
            int number = Convert.ToInt32(Console.ReadLine());
            float gravity = (number * 0.17f);
            Console.WriteLine(gravity.ToString("F3"));
        }
    }
}

I need it to output a single floating-point value and all values must be with exactly 3-digit precision after the floating point. I got it to work, the only problem is that it crashes if I don't input a whole number. That's the error i get.

Unhandled Exception: System.FormatException: Input string was not in a correct format. at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Convert.ToInt32(String value) at MoonGravity.MoonGravity.Main(String[] args) in .... 2015\Projects\ConsoleApplication3\ConsoleApplication3\Program.cs:line 13

I know the problem comes from my Convert.ToInt32 and I tried to fix it but i couldn't. Thank you for the help.

3

3 Answers

0
votes

Below line is incorrect:

int number = Convert.ToInt32(Console.ReadLine());

An integer (from the Latin integer meaning "whole") is a number that can be written without a fractional component. For example, 21, 4, 0, and −2048 are integers, while 9.75, 5 1⁄2, and √2 are not.

change it to decimal, double or float

decimal number = Convert.ToDecimal(Console.ReadLine());
3
votes

If you want to be able to input non-whole numbers, perform a different conversion. There are also methods provided in .NET that will try to parse input into another type and give you boolean return for if it succeeded, instead of throwing an exception. Using try parse is especially handy when bringing in user input and you have no idea what they may try to give you. You can then gracefully handle the likely condition that incorrect or invalid input is given, instead of catching a format exception, etc. MSDN Single Try Parse

static void Main(string[] args)
    {
        float number;
        var success = Single.TryParse(Console.ReadLine(), number);
        if(success)
        {
            float gravity = (number * 0.17f);
            Console.WriteLine(gravity.ToString("F3"));
        }
        else
        {
            Console.WriteLine("Only numbers allowed.");
        }
    }
2
votes

That's because your number is int. Try changing it to float.

float number = (float)Convert.ToDouble(Console.ReadLine());
float gravity = (number * 0.17f);
Console.WriteLine(gravity.ToString("F3"));