c Language Mistake Rounding Questions

Asked 2 years ago, Updated 2 years ago, 125 views

Running the code below will automatically round up the last real value.

Enter: 4
          15 23.6 100.35 0.388
#include <stdio.h>

int main(void)
{
    int cnt;
    scanf("%d", &cnt);
    double arr[cnt];
    double hap=0;

    for(int i=0; i<cnt; i++)
    {
        scanf("%lf", &arr[i]);
        printf("%.2lf ", arr[i]);
        hap += arr[i];
    }
    printf("\n");
    printf("hap : %.2lf\n", hap);
    printf("avg : %.2lf", hap/cnt);

    return 0;
}

Is it because of %.2lf?

c rounding

2022-09-21 12:12

1 Answers

In accordance with IEEE's recommendation, the OS automatically rounds up and outputs during the output process.

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

int main()
{
    double x = 1.159;
    printf("%.2lf", floor(x * 100) / 100);
    return 0;
}

You can use the above trick.


2022-09-21 12:12

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.