c++中的while循环任务
While loop task in c++
我是 c++ 的初学者,我在使这段代码按我想要的方式工作时遇到了问题。任务是编写一个程序,将所有自然数乘以加载数 n.
为了让它打印出正确的结果,我将 x
除以 n
(见下面的代码)。我怎样才能让它打印 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;
}
首先,您最好尽快习惯一个原则:始终检查用户输入的正确性!
cin >> n;
if(cin && n > 0)
{
// valid
}
else
{
// appropriate error handling
}
不确定,为什么需要 while 循环?在这种情况下,for 循环肯定更好:
int x = 1;
for(int i = 2; i < n; ++i)
x *= i;
如果您仍然想要 while 循环:从 i == 2
开始(反正 1 是中性的)然后递增:
i = 2;
while(i < n)
{
x *= i;
++i;
}
在 n == 1
的情况下,根本不会输入循环(任一变体),你没问题...
How can I make it so that in the last cout
I can only put x and not have to divide x by n to get the correct answer?
最好使用for
循环。
// This stops when i reaches n.
// That means, n is not multiplied to the result when the loop breaks.
for (int i = 1; i < n; ++i )
{
x *= i;
}
cout << "The result is: " << x <<endl;
您已经有两个很好的选择,但是当您在编程中足够自在时,您可能想看看另一个:
unsigned factorial(unsigned value)
{
if (value <= 1)
{
return 1;
}
else
{
return value * factorial(value - 1);
}
}
这是一个递归函数,在适当的时候使用它会很整洁(不幸的是,这里不可能是这种情况,因为执行堆栈可能会变得如此之大,以至于在你完成之前就填满了你的记忆。但是你可以查看它以了解有关递归函数的更多信息)
当您的内存已满时,您的应用程序就会因所谓的堆栈溢出而崩溃。
我是 c++ 的初学者,我在使这段代码按我想要的方式工作时遇到了问题。任务是编写一个程序,将所有自然数乘以加载数 n.
为了让它打印出正确的结果,我将 x
除以 n
(见下面的代码)。我怎样才能让它打印 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;
}
首先,您最好尽快习惯一个原则:始终检查用户输入的正确性!
cin >> n;
if(cin && n > 0)
{
// valid
}
else
{
// appropriate error handling
}
不确定,为什么需要 while 循环?在这种情况下,for 循环肯定更好:
int x = 1;
for(int i = 2; i < n; ++i)
x *= i;
如果您仍然想要 while 循环:从 i == 2
开始(反正 1 是中性的)然后递增:
i = 2;
while(i < n)
{
x *= i;
++i;
}
在 n == 1
的情况下,根本不会输入循环(任一变体),你没问题...
How can I make it so that in the last
cout
I can only put x and not have to divide x by n to get the correct answer?
最好使用for
循环。
// This stops when i reaches n.
// That means, n is not multiplied to the result when the loop breaks.
for (int i = 1; i < n; ++i )
{
x *= i;
}
cout << "The result is: " << x <<endl;
您已经有两个很好的选择,但是当您在编程中足够自在时,您可能想看看另一个:
unsigned factorial(unsigned value)
{
if (value <= 1)
{
return 1;
}
else
{
return value * factorial(value - 1);
}
}
这是一个递归函数,在适当的时候使用它会很整洁(不幸的是,这里不可能是这种情况,因为执行堆栈可能会变得如此之大,以至于在你完成之前就填满了你的记忆。但是你可以查看它以了解有关递归函数的更多信息)
当您的内存已满时,您的应用程序就会因所谓的堆栈溢出而崩溃。