When I enter 2
, I wish to get this output:
value: 2.4
But when I do the multiplication, I am getting this:
value: 2.400000
This is my code:
#include <stdio.h>
int main()
{
float num;
float result;
printf("Number: ");
scanf("%f", &num);
result = num * 1.2;
printf("Result: %f", result);
}
What can I do?
CodePudding user response:
You need to change your printf() to this:
printf("Result: %.1f", result);
The number after the .
and before the f
is the precision that specifies the number of digits after the decimal point of a floating-point value.
CodePudding user response:
You can specify how many digits you want to print after the decimal point by using %.Nf
where N
is the number of digits after the decimal point. In your use case, %.1f
: printf("Result: %.1f", result)
.
There are some other issues in your code. You are making use of scanf()
, but you are not checking its return value. This may cause your code to break.
scanf()
returns the number of arguments it successfully parsed. If, for any reason, it fails, it doesn't alter the arguments you gave it, and it leaves the input buffer intact. This means whenever you try again and read from the input buffer, it will automatically fail since
- it previously failed to parse it, and
- it didn't clear it, so it's always there.
This will result in an infinite loop.
To solve the issue, you need to clear the input buffer in case scanf()
fails. By clearing the buffer, I mean read and discard everything up until a newline (when you previously pressed Enter) is encountered.
void getfloat(const char *message, float *f)
{
while (true) {
printf("%s: ", message);
if (scanf("%f", f) == 1) break; // Break only if the user entered a "valid" float number.
scanf("%*[^\n]"); // Read an discard everything up until a newline is found.
}
}
You can use it in your main like that:
int main(void) // Note the void here when a function doesn't take any arguments
{
float num;
float result;
getfloat("Number", &num);
result = num * 1.2;
printf("Result: %.1f", result); // Print only one digit after the decimal point.
}
Sample output:
Number: x
Number: x12.45
Number: 12.75
Result: 15.3