C编程为什么浮点值改变

时间:2018-08-30 14:47:34

标签: c arrays loops floating-accuracy

我需要有关此程序的帮助。浮点数组购买[2]的值为90.50,但是当我运行代码时,它从90.50变为90.5010.990000。为什么?采购[0]和采购[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);
}

3 个答案:

答案 0 :(得分:3)

打印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

答案 1 :(得分:0)

此:

  

90.5010.990000

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

更改此:

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

对此:

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

答案 2 :(得分:0)

感谢@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);
}