natural number problem

Hi everyone!

I have a problem, which I should solve till tomorrow morning. My task is to raise a real number to its nth degree, where n is a natural number, without using the actual operation of raising to a degree.

My program works well, except for the part where I check if the input is right. The program should return with an error message and ask for the number again. But if I give it a fractal number instead of a natural, it terminates, working with the integral part. Although it should ask for the exponent again.


Here's this part of my code:

cout << "The exponent: " << endl;
cin >> n;

if (cin.fail()!=0 || n<0 || n%1!=0) {
do{
cin.clear();
cin.ignore(1000,'\n');
cout << "Error! Give the exponent again!: ";
cin >> n;
}
while(cin.fail()!=0 || n<0 || n%1!=0);
}


Why isn't my solution (dividing n by 1 and if the remainder isn't 0 then n isn't an integer number) working? Can you come up with something, which makes sure the program works well with only natural exponents?

Thank you very much in advance!
n%1 doesn't work since to do % n already has to be an integer. The .5 in 2.5 is dropped on line cin >> n.
You could instead read a float f and check if f == int(f).
The problem is that reading verified input is actually a really tricky thing to do.

http://www.cplusplus.com/forum/beginner/13044/#msg62827

All the important stuff is on lines 30 through 41 -- read an entire line as a string, get rid of trailing whitespace, try to read it as your target, and check to see if anything was left over.

You can put it directly in your input code, or you can write a function. (Mine is really just a really, really fancy function.)

I think there's an Article on this too... but I can't find it off the top of my kbd

Good luck!
Thank you very much! It's working fine now.:)
Topic archived. No new replies allowed.