Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

C 小数精度


设置小数精度

你可能已经注意到,如果你打印一个浮点数,输出将显示小数点后的很多位数字。

示例

float myFloatNum = 3.5;
double myDoubleNum = 19.99;

printf("%f\n", myFloatNum); // 输出 3.500000
printf("%lf", myDoubleNum); // 输出 19.990000
自己试试 »

如果你想删除额外的零(设置小数精度),可以使用一个点 (.) 后面跟着一个数字,该数字指定小数点后应该显示多少位数字。

示例

float myFloatNum = 3.5;

printf("%f\n", myFloatNum);   // 默认情况下,小数点后将显示 6 位数字
printf("%.1f\n", myFloatNum); // 只显示 1 位数字
printf("%.2f\n", myFloatNum); // 只显示 2 位数字
printf("%.4f", myFloatNum);   // 只显示 4 位数字
自己试试 »

C 练习

通过练习测试自己

练习

使以下示例的输出只显示小数点后 **一位数字**。

float myScore = 9.5;
printf("", myScore);

开始练习



×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.