而在c ++中循环任务

Bin*_*ary 3 c++ counter cout while-loop

我是c ++的初学者,我遇到了使这段代码按照我想要的方式工作的问题.任务是编写一个程序,将所有自然数乘以加载数n.

为了使打印出正确的结果,我分xn(见下面的代码).如何进行打印x而不必将其除以n得到正确的答案?

#include<iostream>
using namespace std;
int main(){
    int n,x=1;
    int i=0;
    cout<<"Enter a number bigger than 0:"<<endl;
    cin>>n;
    while(i<n){
        i++;
        x=i*x;  
    };
    cout<<"The result is: "<<x/n<<endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Aco*_*gua 6

首先,您最好尽快习惯:始终检查用户输入是否正确!

cin >> n;
if(cin && n > 0)
{
    // valid
}
else
{
    // appropriate error handling
}
Run Code Online (Sandbox Code Playgroud)

不确定,为什么你需要一个while循环?在这种情况下,for循环肯定更好:

int x = 1;
for(int i = 2; i < n; ++i)
   x *= i;
Run Code Online (Sandbox Code Playgroud)

如果你仍然想要while循环:开始时i == 2(1仍然是中性)然后增加:

i = 2;
while(i < n)
{
    x *= i;
    ++i;
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下n == 1,循环(任何变种)根本不会输入,你很好......