-3

In this program, the float array purchases[2] value is 90.50 but when I run the code it changes from 90.50 to 90.5010.990000. Why? purchases[0] and purchases[1] print fine.

#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);
}
halfer
  • 19,824
  • 17
  • 99
  • 186
ziggelflex
  • 23
  • 4
  • 6
    `"%.2f %.2f %.2f"` - There's no new line here – StoryTeller - Unslander Monica Aug 30 '18 at 14:48
  • @P__J__: The complaint in this question is about “90.5010.990000”, which is caused by a missing new-line character in a `printf` and has nothing to do with floating-point arithmetic. Please do not mark questions as a duplicate of [that question](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) simply because they contain floating-point somewhere within them. – Eric Postpischil Aug 30 '18 at 21:00

3 Answers3

3

When you print the contents of the purchases array, you don't print a newline. So when you print total for the first time in the loop it appears on the same line.

Add the newline:

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

Output:

10.99 14.25 90.50
10.990000
0
25.240000
1
115.739998
2
Purchases total is 115.74
dbush
  • 205,898
  • 23
  • 218
  • 273
0

This:

90.5010.990000

is 90.50, and then, 10.990000. You forgot to use a newline.

Change this:

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

to this:

printf("%.2f %.2f %.2f/n", ..
gsamaras
  • 71,951
  • 46
  • 188
  • 305
0

Thanks @StoryTeller. No new line! School boy error right.

Should be:

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

Sorry to bother you all.

#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);
}
ziggelflex
  • 23
  • 4