C ++ extraction of decimal solution error

A simple question in C ++, since you can see that it creates a table and enters the variable a, as well as the variable t answer, the problem is that I do not know how to fix if () . As you can see, he has an error (typo). I donโ€™t know how to determine if the variable t has an example: 1 or 1.5 if the number is 1. (something is here and it is more than the number. 1 ), then call one else condition and call the other.

 int a,b = 18; double t; for (a = 0; a <= b; a++) { t = 8 + (double)(18 - a) / 2; if (t >= *.1) cout << setw(9) << a << setw(20) << fixed << setprecision(1) << t << endl; else cout << setw(9) << a << setw(20) << t << endl; } 

I tried:

 #include <iostream> #include <iomanip> #include <cmath> #include <math.h> using namespace std; int main () { int a,b = 18; double t; for (a = 0; a <= b; a++) { t = 8 + (double)(18 - a) / 2; if (modf(t, NULL) >= 0.1) cout << setw(9) << a << setw(20) << fixed << setprecision(1) << t << endl; else cout << setw(9) << a << setw(20) << t << endl; } } 

Fixed in his own way, still thanks to "Angew", he first published modf ():

 #include <iostream> #include <iomanip> #include <cmath> #include <math.h> using namespace std; int main () { int a,b = 18; double t,z; int k; for (a = 1; a <= b; a++) { t = 8 + (double)(18 - a) / 2; if (modf(t, &z) >= 0.5) cout << setw(9) << a << setw(20) << fixed << setprecision(1) << t << endl; else k = t; cout << setw(9) << a << setw(20) << k << endl; } } 
+4
source share
3 answers

Perhaps you are looking for std::modf ?

 double wholePart; if (std::modf(t, &wholePart) >= 0.1) 
+4
source

Have you tried to use the module instead of division? (% symbol) This will return the remainder of your operation.

 double x = 1.1; x = x % 1.0; //x is equal to .1 

Searching for the mod of your number and 1 will return the decimal remainder, so change the if statement to

 if (t % 1.0 >= 0.1) 
+2
source

This will find the decimal part of your number:

 double num = 23.345; int intpart = (int)num; double decpart = num - intpart; //decpart = .345 

As BoBTfish mentioned, this can become a problem with large decimal places. Another possible (safe) solution:

 double integral; double fractional = modf(some_double, &integral); 

with this, your if will become ..

 if(t_decpart >= .1) // 
+1
source

Source: https://habr.com/ru/post/1479754/


All Articles