0

Hi i have program which prints in table X and cos(x) with use libery cmath. I put beginning, end of interval, and k - number of steps. but when x is 0.1 and do -0.1+0.1 it give me weird x.

#include <iostream>
#include <cmath>

using namespace std;
int main() {
    double a;
    double b;
    double k;
    int l=1;
    cout << "Podaj a przedzialu: ";
    cin >> a;
    cout << "Podaj b przedzialu: ";
    cin >> b;
    cout << "Podaj krok: ";
    cin >> k;
    if(k<=0 || b<a )
    {
        cout << "podaj przedzial od mniejszego do wiekszego lub dodatni krok";
    }
    else
    {
        while(a<=b)
        {
            cout << "krok " << l << ": [x=" << a << "\t cos(" << a <<")=" << cos(a) << endl;
            a+=k;
            l++;
        }
    }

}

and output is:

Podaj a przedzialu:-1
 Podaj b przedzialu:0
 Podaj krok:0.1
 krok 1: [x=-1        cos(-1)=0.540302
krok 2: [x=-0.9  cos(-0.9)=0.62161
krok 3: [x=-0.8  cos(-0.8)=0.696707
krok 4: [x=-0.7  cos(-0.7)=0.764842
krok 5: [x=-0.6  cos(-0.6)=0.825336
krok 6: [x=-0.5  cos(-0.5)=0.877583
krok 7: [x=-0.4  cos(-0.4)=0.921061
krok 8: [x=-0.3  cos(-0.3)=0.955336
krok 9: [x=-0.2  cos(-0.2)=0.980067
krok 10: [x=-0.1         cos(-0.1)=0.995004
krok 11: [x=-1.38778e-016        cos(-1.38778e-016)=1

Process finished with exit code 0

thanks for help !

Gerhardh
  • 11,688
  • 4
  • 17
  • 39
  • Your problem is that in all modern computer languages, adding `0.1` to `-0.9` will not give you `-0.8`. And that's where the "weird" values come from. See the linked question for more information. – Sam Varshavchik Mar 06 '22 at 21:28
  • when you are dealing with doubles or floats, results of operations are seldom exactly equals to a number, it is usually a very close approximation. The number you see is very close to 0, but is not exactly 0. So, writing loops with 'a == 0' in double world is not guaranteed to work in all the cases. You can use integers to organize your increments instead and using cos(i / 10.0) if you need to have a precise 0. – Serge Mar 06 '22 at 21:32
  • 1
    Note that your program would be easier for other people to understand if you translated the output to English. – Andreas Wenzel Mar 06 '22 at 21:36
  • @Serge, yes, i can, but sometime i put k=0.1 and sometime 0.01 ald some time 1, have u solution for that? – malinowynosek_ Mar 07 '22 at 00:04

0 Answers0