N
N
nkorobkov2015-12-01 16:54:14
C++ / C#
nkorobkov, 2015-12-01 16:54:14

Why is there an error when adding 0.1 to a number in a loop?

Here is a C program:
When you enter step dx=0.1 in a loop, an error occurs after the 27th iteration...
What is it from, and how to solve it?

#include <stdio.h>
#include <stdlib.h>

int main(){
    float a, b, c, result, dx, x1, x2, i;

    printf("Enter A\n");
    scanf("%f", &a);

    printf("Enter B\n");
    scanf("%f", &b);

    printf("Enter C\n");
    scanf("%f", &c);

    printf("Enter X1\n");//X1 начальный
    scanf("%f", &x1);

    printf("Enter X2\n");//X2 конечный
    scanf("%f", &x2);

    printf("Enter step - dx\n");
    scanf("%f", &dx);

    printf("\nA = %f\n", a);
    printf("B = %f\n", b);
    printf("C = %f\n", c);
    printf("X1 = %f\n", x1);
    printf("X2 = %f\n\n", x2);
    printf("Step dx = %f\n\n", dx);

    if(x1 < 0 && b != 0){
        printf("X1:\t\tResult:\n\n");
        for(; x1 <= x2; x1+=dx){
            result = a*x1*x1+b;
            printf("%f\t%f\n", x1, result);
        }
    }
    else if(x1 > 0 && b == 0){
        printf("X1:\t\tResult:\n\n");
        for(; x1 <= x2; x1+=dx){
            result = (x1 - a)/(x1 - b);
            printf("%f\t%f\n", x1, result);
        }
    }
    else{
        printf("X1:\t\tResult:\n\n");
        for(; x1 <= x2; x1+=dx){
            result = x1/c;
            printf("%f\t%f\n", x1, result);
        }
    }
    return 0;
}

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
sunrails, 2015-12-01
@sunrails

habrahabr.ru/post/112953

O
Oleg Tsilyurik, 2015-12-01
@Olej

What is it from, and how to solve it?

Nonsense in the question/code is written - unmeasured:
1. "From what" -> Why
2. the for loop is never organized by real types, but should be organized by enumerated types ... mainly int variants
3. your written for loop is poorly written while loop...
4. real values ​​should never be compared for equality ... and certainly should never be a while loop criterion
5. all real operations are approximate , and the condition x1 == x1+ dx, for example, under certain conditions can be true: adding to a number won't change it (think when?)
Sit down - two! ;-)

R
Rsa97, 2015-12-01
@Rsa97

Because the number 0.1 10 = 0.0(0011) 2 is irrational in the binary system, so it has an error in any final representation.

V
Vladimir Martyanov, 2015-12-01
@vilgeforce

float features. The variable stores a number with an error, this is the data format.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question