如果 else 语句不断循环

If else statement keeps looping infinetely

本文关键字:循环 语句 else 如果      更新时间:2023-10-16
#include <iostream>
using namespace std;
int factorial(int n){ //Aprēķina skaitļa faktoriali izsaucot pati sevi
if(n > 1)
return n*factorial(n - 1);
else
return 1;
}
int main(){
int ok;
do{

int n;
cout << "Enter a integer: ";
cin >> n;
int x=factorial(n);
cout << "Factorial=" << x << endl;
for(int a=1;(a+2)<(x/2+1);a++){ 
if(a*(a+1)*(a+2)==x)
cout << "Equals " << a << "*" << a+1 << "*" << a+2 << endl;
else 
cout<<"Cant be a multiplication of 3 numbers"<<endl;
}
cout << " Do you want to continue (1) or end (0)?" << endl;
cin >> ok;
}
while (ok==1);
}

所以嘿,我得到了这段代码,它有一个阶乘函数,它检查阶乘是否可以是 3 个连续数字的乘法

for(int a=1;(a+2)<(x/2+1);a++){ 
if(a*(a+1)*(a+2)==x)
cout << "Equals " << a << "*" << a+1 << "*" << a+2 << endl;
else 
cout<<"Cant be a multiplication of 3 numbers"<<endl;
}

我现在在这部分遇到了一个问题,例如,如果我输入 8,它会发出阶乘 40320 和"不能是 3 个数字的乘法"的无限垃圾邮件,此外,当我输入 1 或 2 时,它不会垃圾邮件"不能是 3 个数字的乘法"它只是给出阶乘 1 或 2 提前感谢您的帮助!!

您需要在以下语句后添加break;语句:

cout<<"Cant be a multiplication of 3 numbers"<<endl; 

我相信输入 1 或 2 的问题是数学:

int a=1;(a+2)<(x/2+1);a++;