12 and 12.5

Hello everyone!
I am new to this programming world.
I recently wrote a program that prints the sum of the series 1 + 1/2 + 1/3 +...+1/n.

It works perfectly for integers, but how do i get it to say display an error message when someone enters a floating point number.
Right now my program treats 12.5 as 12 and prints the output.

Thanks!




You must have declared some variable int rather than float or double.
Post the code, if you didn't find the problem already.
If you are cin>>ing into a int, it will stop at the radix point as that isn't a valid number. You would have to read all the data in as, say, a string, then check to see if there are any invalid characters. You could also read the data then check to see if there is anything other than a newline left, and if so, complain.
I prefer the latter.

Here's an improved version of an answer I gave 1 1/2 months ago... (This is the first method...)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
cout << "Please enter an integer in the range [19, 37]: " << flush;
int n;
while (true)
  {
  cin >> n;

  if ((cin) && (n >= 19) && (n <= 37))
    break;

  cin.clear();
  cin.ignore( 1000, '\n' );
  cout << "Hey, follow instructions please: " << flush;
  }
cin.ignore( 1000, '\n' );
cout << "Good job!\nYou entered the number '" << n << "'.\n";

There is also this (which is my prefered method):
http://www.cplusplus.com/forum/beginner/13044/page1.html#msg62827

:-)
Last edited on
Topic archived. No new replies allowed.