简体   繁体   English

C 中的 printf():如何防止浮点数/双精度数舍入?

[英]printf() in C: How do I keep my floats/double from rounding?

Been trying to get the outputs to give me the number without rounding, not sure what I'm missing一直试图让输出给我没有四舍五入的数字,不知道我错过了什么

float NumberOfTrees1;

for (NumberOfTrees1 = 1000.0; NumberOfTrees1 >= 50; NumberOfYears++)
{
    NumberOfTrees1 = NumberOfTrees1 - (NumberOfTrees1 * 0.13);
    printf("Number of Remaining Trees: %0.1f\n",NumberOfTrees1);
}

My Output:我的 Output:

Number of Remaining Trees: 61.7
Number of Remaining Trees: 53.7
Number of Remaining Trees: 46.7

Required Output:所需 Output:

Number of Remaining Trees: 61
Number of Remaining Trees: 53
Number of Remaining Trees: 46

I understand that the %0.1f is what gives me the .7 but when I use %0.0f it rounds up my numbers which I don't want.我知道%0.1f是给我.7的原因,但是当我使用%0.0f时,它会四舍五入我不想要的数字。 Been switching things around from using int , double , long float etc to no avail.一直在使用intdoublelong float等进行切换,但无济于事。

Any help would be great and thank you in advance!!!任何帮助都会很棒,提前谢谢你!!!

Antonin GAVRELs answer should print the desired output, but if you don't want to cast the floating point numbers into integers, you could use the double floor (double x) function from <math.h> . Antonin GAVREL的答案应打印所需的 output,但如果您不想将浮点数转换为整数,则可以使用<math.h>中的double floor (double x) function。

#include <math.h>
#include <stdio.h>

int main(void)
{
    double x =  53.7;
    double floored = floor(x);
    printf("⌊%0.1lf⌋ = %0.1lf\n", x, floored);

    return 0;
}

The program can be compiled with -lm and prints the following when executed:该程序可以使用-lm编译并在执行时打印以下内容:

⌊53.7⌋ = 53.0

You can cast into int in order to truncate your number:您可以转换为int以截断您的号码:

int main(void) {
    double d =  53.7;
    float f = 46.7f;

    int a = (int)d;
    int b = (int)f;

    printf("%d %d\n", a, b);
}

output: output:

53 46

Or, as suggested by @user3386109, you may use floor(), but you will need to also include <math.h> header and compile with -lm或者,正如@user3386109 所建议的,您可以使用 floor(),但您还需要包含 <math.h> header 并使用-lm编译

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM