简体   繁体   中英

An error with Floating Point Exception C++ expression

I'm beginner to C++ and try to get the digits of a number like 110. I tried the following code but got Floating Point Exception C++ error. I can not understand what goes wrong.

  int main()
{
 int p = 10;
 int j = 1;
while(110 % p >=1 || 110 % p ==0){
    cout<<110 % p;
    j++;
    p = p *10;
}
}

Can any one correct the code?

The problem you have is that your modulus is a remainder, if you think mathematically about what you're doing it doesn't make sense. When you divide a number into another number, there's either a remainder, or there is not. You're continuing in the loop for as long as there is or is not a remainder. This results in an integer overflow on p.

Try this:

#include <iostream>

using namespace::std;

int main()
{
  // this prints out the digits backwards:
  for(int InitialNumber=110;InitialNumber!=0;InitialNumber/=10){
    int LastDigit=InitialNumber%10;
    cout<<LastDigit<<endl;
  }
  return 0;
}

Output:

martyn@localhost ~ $ g++ test.cpp -std=c++11
martyn@localhost ~ $ ./a.out 
0
1
1

If you persisted with your algorithm you could terminate it like this:

int main()
{
  int p = 10;
  int j = 1;
  while( p < 110*10 ){
    cout<<110 % p<<endl;
    j++;
    p = p *10;
  }
}

That would stop the loop going for ever and overflowing P. And that would give you:

martyn@localhost ~ $ ./a.out 
0
10
110

Which i suspect isn't what you wanted, instead you'd want to just have the first digit, so you need to divide the output by the previous power of ten like this:

int main()
{
  int p = 10;
  while( p < 110*10 ){
    cout<<(110 % p)/(p/10)<<endl;
    p = p * 10;
  }
}

And that would give you:

martyn@localhost ~ $ g++ test.cpp -std=c++11
martyn@localhost ~ $ ./a.out 
0
1
1

But i suspect the first code excerpt is more elegant. Note that in all of these examples the digits are printed out back to front. This may not be what you want.

First of all, your code runs into an infinite loop . I modified your program to print p after every step . The output was :
在此处输入图片说明
You can't do % operation with 0 as second operand .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM