There is a part of the sentence that I don't understand about the mistake

Asked 1 years ago, Updated 1 years ago, 92 views

1.

#include <stdio.h>

int main(void){
    double a,b;

    scanf("%lf %lf",&a,&b);

    while( a < b ){
        printf("%0.2lf ",a);
        a = a+0.01;
    }
}

2.

#include <stdio.h>

int main(void){
    int a,b;

    scanf("%d %d",&a,&b);

    while( a < b ){
        printf("%d ",a);
        a = a+1;
    }
}

The first and second codes are designed to create a function that allows you to print from the first number to the second number to the previous number If you type 2.00 2.03 in the first code, you get 2.00 2.01 2.02 2.03 If you type 0 3 in the second code, only 012 comes out I added 0.11 for both of them, but why is it 2.03 on the top and only 2 on the bottom? Is there anything special about mistakes?

while-loop

2022-09-22 18:37

2 Answers

Just in case, I looked it up on c double comparison and found that it is difficult to compare double-type data in C.

double d1 = 13+0.2+0.2+0.1;       /*  13.5 ? */
double d2 = 14-0.2-0.2-0.1;       /*  13.5 ? */

if(d1==d2)
{
    printf("They're the same %lf %lf\n",d1,d2);
}
else
{
    printf("They're not the same %lf %lf\n",d1,d2);
}

# Output: They're not the same 13.500000 13.500000


2022-09-22 18:37

A decimal representation cannot accurately represent 1/3 as a finite number of decimal places. (0.333... Since is an infinite number.) 1/3 can only be expressed accurately as a limited decimal place if it is expressed as a triad. (1/3 is a binary 0.1, i.e. finite decimal)

Since computers use binary representations internally, it is possible that decimal finite decimals cannot be accurately represented (stored) in finite digits. This is why you should be careful when using floating-point types.


2022-09-22 18:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.