Need help how to output that a number is a whole number

the bottom line is really what I am needing help with I thought that I could use a wildcard to make the program recognize that any number with a decimal (.1 through .9 is not a whole number). Any help is much appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

using namespace std;

 int main()
   {
 double i ;

 cout << "Enter a number: " << endl ;
 cin >> i ;
 cout << "The number you entered is " ;
 if( i/2*2 == i )
   cout << "even" << endl ;
  else
   cout << "odd" << endl ;

 if( i = *.1, *.2, *.3, *.4, *.5, *.6, *.7, *.8, *.9)
	cout << "You have entered a decimal.";
  else
   cout << "You have entered a whole number.";
   }

Use this predicate if (i == (int)i).
Thanks aruawons. I just switched my couts and voila. Would you mind explaining what exactly that predicate does (break it down for me) please. Much appreciated!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

using namespace std; 

 int main() 
   {
 double i ;

 cout << "Enter a number: " << endl ;
 cin >> i ;
 cout << "The number you entered is " ;
 if( i/2*2 == i )
   cout << "even" << endl ;
  else
   cout << "odd" << endl ;

 if( i == (int)i)
	cout << "You have entered a whole number.";
  else
   cout << "You have entered a decimal.";
   }
Last edited on
Since i is originally a double, (int)i (called "type casting") converts it to an int by truncating all the decimal part. If a number retains its value after such a truncation, it gotta be a whole number.
I think it just clicked by putting i == (int)i is sort of "redeclaring" i as an integer and the == is telling the program that double i is the same as int i. ok thanks again aruawons.
I think it just clicked by putting i == (int)i is sort of "redeclaring" i as an integer and the == is telling the program that double i is the same as int i.


No, not at all. That's a complete misunderstanding.

(int)i gives an int value. Not i. It does not give you i. i is some other variable. (int)i gives you a temporary variable, which will be an integer - it will be whatever integer you would get if you converted the double i into an int, because that's exactly what it does. Takes the double value i and creates a new int based on that value.

== is telling the program that double i is the same as int i.

No, it is not.

== asks the program if the value on the left is identical to the value on the right. It in no way tells the program that something is the same as something else. That is the complete opposite; it asks if something is the same as something else.
Last edited on
Oh ok thanks moschops for describing that for me.
Topic archived. No new replies allowed.