0

We have Homework about loops that displays two computations and increments a variable by the inputted i. These codes run and all is well until I input a=1, b=3 i=0.2, what happens is that it won't reach to 3 even if the while condition is a<=b. The only time it works when a=1, b=2, and i=0.2

#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

double inputI(double i){
    for(i=0;i<=0;cin>>i){
        cout<<"i must be greater than 0"<<endl;
        cout<<"Input i: ";
    }
    return i;
}

double compX(double s, double b){
    double x;
    x = s/cbrt(b)+2*pow(s,2);
    return x;
}

double compY(double s, double x){
    double y;
    y = (x+s/x)+3*s;
    return y;
}

void display(double x, double y,double a){
    cout<<fixed<<setprecision(2)<<a<<"\t";
    cout<<fixed<<setprecision(4);
    cout<<x<<"         "<<y<<endl;
}

int main(){
    double x,y,a,b,i;

    cout<<"Input a: ";
    cin>>a;
    cout<<"Input b: ";
    cin>>b;
    i = inputI(i);
    //is there something wrong???
    do{
        x = compX(a,b);
        y = compY(a,x);
        display(x,y,a);
        a+=i;
    }while(a<=b);

}
Kunal Puri
  • 3,419
  • 1
  • 10
  • 22
Plopop
  • 1
  • 1
  • Why do you pass (the uninitialized) `i` to `inputI`? – Davis Herring May 10 '19 at 02:44
  • What does it do that you don't expect? – Shawn May 10 '19 at 03:02
  • 3
    Remember that `double`s are floating point numbers and they are not exact. It might look like `a` equals `b`, but `a` could really be 0.99999999999997 and `b` could be 1.000000000003 and fail the test for equality. See [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) for more details. – user4581301 May 10 '19 at 03:06

2 Answers2

0

You to correct the following warning:

warning C4700: uninitialized local variable 'i' used

For example:

double x,y,a,b,i = 0;

enter image description here

Black Frog
  • 11,595
  • 1
  • 35
  • 66
  • This is a problem, but not one likely to result in the error reported. This will most likely just screw up the user input because `i` enters `inputI` in a non-zero and possibly positive state. But it could also end the world because, you know, UB. – user4581301 May 10 '19 at 03:13
  • Yeah agree with @user4581301, the variables are set before they are used so don't think this is the cause. – mojo1mojo2 May 10 '19 at 04:19
  • I just initialize the variable to ZERO and the current code works. Hence the output I added to my answer. No magic code change. – Black Frog May 10 '19 at 11:31
0

This is a floating-point precision issue with comparison of doubles. These seems to have worked for me:

bool double_less_than(double a, double b, double epsilon = 0.001)
{
    return a < b + epsilon;
}

int main()
{
    ...
    do{
        ...
    }while(double_less_than(a, b, 0.000001));
}
mojo1mojo2
  • 1,062
  • 1
  • 18
  • 28