如果 else 语句不断循环
If else statement keeps looping infinetely
#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++;
相关文章:
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 如果 else 语句不断循环
- do while 循环中的 if 语句以 yes 或 no 结尾
- 带有开关语句的 do-while 循环 -- 无穷循环错误
- 如果语句不会在 do - while 循环中运行
- 有没有办法在循环中的条件至少满足一次时运行语句?
- 什么可以用来替换代码中的循环和 if 语句?
- C++ 访问 if 语句(如果它们在 for 循环中)
- for 循环后的分号是什么意思?为什么第一个循环语句中有 j++
- 这段代码如何在没有任何循环语句或'goto'或递归的情况下循环?
- 终端不阅读循环语句
- 我的值不断增加,而不是在循环语句中重置
- 此 for 循环语句的正确语法
- 神秘的 for 循环语句
- do 循环语句导致无限循环
- 嵌套循环语句结果不正确
- 在 FOR 循环语句的条件部分中使用声明
- 构造长循环语句是一种好的做法吗
- 在条件C++循环语句中向SQLite3表中插入条目
- 循环语句警告的冒泡排序算法