编码它受到不需要它的 cout 影响的代码

问题描述

该程序只是有一个函数来检查一个数字是否是一个完美的数字。完美是其所有因素(不包括数字本身)的总和等于数字本身。喜欢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 无关。查看 isPerfect 函数中的循环。变量 i 具有未定义的值,因为它未初始化。像这样初始化它:

for(int i = 1; i<a; i++){