【发布时间】:2020-12-23 09:01:12
【问题描述】:
该程序只是有一个函数来检查一个数字是否是一个完美的数字。完美是其所有因素(不包括数字本身)的总和等于其自身的数字。喜欢6(1 + 2 + 3 = 6) 也喜欢28
我看到了一个奇怪的行为。有cout << ""。如果我们删除此行代码将无法正常工作,如果我们把它一切工作正常。这个我看不懂
#include<iostream>
using namespace std;
int IsPerfect(int);
int main(){
int N, j;
cout << "Enter a value for N: ";
cin >> N;
cout << "Perfect numbers are ";
for(j=1; j<=N; j++){
cout << ""; //If you remove this line no output will be printed
if(IsPerfect(j) == 1){
cout << j << endl;
}
}
}
int IsPerfect(int a){
int sum=0;
for(int i; i<a; i++){
if(a%i == 0){
sum=sum+i;
}
}
if(sum == a){
return 1;
}
else{
return 0;
}
}
【问题讨论】:
-
cout << ""无关紧要。无论如何,您都有未定义的行为,因为来自for(int i; i<a; i++){的i未初始化使用。打开所有编译器警告以发现此类错误。