Floating point

Why does this code print "k>0.1"? And how to solve this problem?
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <conio.h>

int main(){
    float k=10-9.9;
    if(k>0.1)
      std::cout<<"\nk>0.1";
    else std::cout<<"\nk<=0.1";
    getch();
}
I think you mean

1
2
3
4
    if(k>0.1)
          std::cout<< k << "\n";
    else 
          std::cout<< k<< "\n";
almost mobotus...

i think he wants it to say 'value of k' "> 0.1"

so it would be
1
2
3
4
if (k>0.1)
    std::cout<< k << " > 0.1 \n";
else
    std::cout<< k << " <= 0.1 \n"


so basically exactly the same as what you have put but with added 0.1's :D
float has its limits as you see from the following examples:

1
2
3
4
5
6
7
8
9
10
#include <iostream>

int main(){
    float k=10-9.9;
    std::cout.precision(15);
    std::cout << k;
    if(k>0.1)
      std::cout<<"\nk>0.1";
    else std::cout<<"\nk<=0.1";
}
0.100000001490116
k>0.1


1
2
3
4
5
6
7
8
9
10
#include <iostream>

int main(){
    double k=10-9.9;
    std::cout.precision(15);
    std::cout << k;
    if(k>0.1)
      std::cout<<"\nk>0.1";
    else std::cout<<"\nk<=0.1";
}
0.0999999999999996
k<=0.1

I think now is OK, isn't it?
Sorry, using Linux box I don't need the console stuff(getch() and so on)
Last edited on
yes. I has a fucntion
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int Calculator(float a,float b,float c,char ch){
     float temp;
     switch(ch){
        case '+': temp=a+b;
                  break;
        case '-': temp=a-b;
                  break;
        case '*': temp=a*b;
                  break;
        case '/': temp=a/b;
                  break;                 
     }
     double k=fabs(c-temp);
     double d=0.1;
     if(d<k)
          return 0;            
     return 1;               
}

in main fucntion
cout<<Calculator(5,5,9.9,'+');
How to make Calculator fucntion return 1?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <cmath>

int Calculator(double a,double b,double c,char ch)
{
     double temp;
     switch(ch){
        case '+': temp=a+b;
                  break;
        case '-': temp=a-b;
                  break;
        case '*': temp=a*b;
                  break;
        case '/': temp=a/b;
                  break;                 
     }
     double k = fabs(c - temp);
     double d = 0.1;
     if(d < k)
          return 0;            
     return 1;               
}

int main()
{
      std::cout << Calculator(5, 5, 9.9, '+');

      return 0;
}
1
Topic archived. No new replies allowed.