C编程为什么浮点值会改变

C Programming Why is the float value changing

我需要有关此程序的帮助。浮点数组 purchases[2] 的值为 90.50,但是当我 运行 代码时,它从 90.50 变为 90.5010.990000。为什么? purchases[0] 和 purchases[1] 打印正常。如有任何帮助,我们将不胜感激。

#include <stdio.h>

int main() {
    float purchases[3] = {10.99, 14.25, 90.50};
    float total = 0;
    int k;

    //Total the purchases
    printf("%.2f %.2f %.2f", purchases[0], purchases[1], purchases[2]); // Just so I know whats going on

    for (k = 0; k < 3; k++) {
        total += purchases[k];
        printf("%f\n", total); // Just so I know whats going on
        printf("%d\n", k);  // Just so I know whats going on
    }

    printf("Purchases total is %6.2f\n", total);
}

这个:

90.5010.990000

是 90.50,然后是 10.990000。您忘记使用换行符了。

改变这个:

printf("%.2f %.2f %.2f", ..

对此:

printf("%.2f %.2f %.2f/n", ..

打印 purchases 数组的内容时,不会打印换行符。因此,当您在循环中第一次打印 total 时,它会出现在同一行。

添加换行符:

printf("%.2f %.2f %.2f\n", purchases[0], purchases[1], purchases[2]);

输出:

10.99 14.25 90.50
10.990000
0
25.240000
1
115.739998
2
Purchases total is 115.74

谢谢@StoryTeller。没有新线!学童错误对。

应该是:

printf("%.2f %.2f %.2f\n", purchases[0], purchases[1], purchases[2]);

不好意思打扰大家

#include <stdio.h>

int main() {
    float purchases[3] = {10.99, 14.25, 90.50};
    float total = 0;
    int k;

    //Total the purchases
    printf("%.2f %.2f %.2f\n", purchases[0], purchases[1], purchases[2]); // Just so I know whats going on

    for (k = 0; k < 3; k++) {
        total += purchases[k];
        printf("%f\n", total); // Just so I know whats going on
        printf("%d\n", k);  // Just so I know whats going on
    }

    printf("Purchases total is %6.2f\n", total);
}