[Solved] input in C programming language


The value have only 2 decimal places is a matter of displaying it, so you just need to print the number of decimal places you are interested in, like

float value = 123.123456;

printf("%.2f\n", value);

if you want to dynamicaly specify that number, you can use

float value    = 123.123456;
int   decimals = 2;

printf("%.*f\n", decimals, value);

If you want to store the value as a string then use sprintf() or better snprintf().

And taking the input with only two decimals does not make sense anyway because the output is what should be filtered instead of the input, note that after all you will ignore the extra decimals inserted by the user.

Also, note that floating point numbers cannot store exact numbers, so even i you leave only two decimal places by doing something like

float value = ((int)(100.0 * 123.1234156)) / 100.0

the actual value that is stored might be

123.1200000001

which has more decimal places.

One thing that you could try is

struct RealNumber
{
    int integerPart;
    int decimalPart;
};

and then handle the input to read them separately, which will be really dificult.

6

solved input in C programming language