The problem of displaying decimal values ​​in program C

The float type of the data type displays decimal numbers. by default, my compiler displays up to 6 decimal places. I want to see only two decimal places. for example, when the compiler performs the operation "c = 2/3", it displays "0.666666667". I want to see only "0.67" on the output screen. so what changes need to be made to program C?

+3
source share
3 answers

You can use the format specifier to limit it to 2 decimal places when outputting a number with printf.

int main() {
  double d = 2.0 / 3.0;
  printf("%.2f\n",d);
  return 0;
}

Here's the conclusion:

---------- Capture Output ----------
> "c:\windows\system32\cmd.exe" /c c:\temp\temp.exe
0.67

> Terminated with exit code 0.
+4
source

, , , - printf("%f", x). "f" , , , printf("%.2f", x).

+1

Print formatting for decimal places is%. followed by the amount of decimal precision followed by "f".

Thus, the display of two decimal places will be

printf("%.2f", i);

and displaying six decimal places will be

printf("%.6f", i);
+1
source

Source: https://habr.com/ru/post/1759215/


All Articles