我想写一个代码,找到比用户的输入更低的完美数字。 样品正确的输出的:为什么我会收到错误“浮点异常”?
输入正整数:100
图6是一个完全数
28被完全数
没有更多完全数小于或等于100
但是当我运行我的代码时,出现错误Floating point exception
并且找不到原因。我究竟做错了什么?
这里是我的代码:
#include <iostream>
using namespace std;
bool isAFactor(int, int);
int main(){
int x, y;
int countOut, countIn;
int userIn;
int perfect = 0;
cout << "Enter a positive integer: ";
cin >> userIn;
for(countOut = 0; countOut < userIn; countOut++){
for(countIn = 1; countIn <= countOut; countIn++){
if(isAFactor(countOut, countIn) == true){
countOut = countOut + perfect;
}
}
if(perfect == countOut){
cout << perfect << " is a perfect number" << endl;
}
perfect++;
}
cout << "There are no more perfect numbers less than or equal to " << userIn << endl;
return 0;
}
bool isAFactor(int inner, int outer){
if(outer % inner == 0){
return true;
}
else{
return false;
}
}
您正在计算x%0. – 2013-04-21 17:42:07
如果您发布了真实的错误消息,这将有所帮助。我很确定没有编译器会说“接受”。在代码中只有整数的浮点错误也有点奇怪。 – 2013-04-21 17:42:45
“浮点收集” 计算进行到x%1。不是吗? 奇怪的是,只有int和bool值才得到该错误消息。这就是为什么我问这个问题:P – user2304913 2013-04-21 18:03:56