C++ "While" 循环
C++ "While" Loop
我正在努力将 "While" 循环应用于以下问题:设计允许用户输入数字的程序的逻辑。显示从 1 到输入数字的每个数字的总和。
Start
int userNumber;
Declarations
int number = 1
while number <= userNumber
++number
endwhile
output number
Stop
我知道我的代码不正确,因为它只是将初始值加一,直到达到用户号码,从而使输出成为用户号码。我将如何在不写出它们的情况下添加每个后续值,例如用户号是10,所以程序会加上1+2+3+4+5+6+7+8+9+10,输出总数55?
谢谢!
这是一个提示。您需要从用户编号开始倒数到 0。像这样:
int finalNum = 0;
int userNum;
//This is where you need to get the user's number....
while(userNum > 0)
{
finalNum += userNum;
userNum--;
}
//Do whatever you need to finalNum....
编辑:您似乎已经post编辑了伪代码;除非另有说明,否则通常在这里是一个很大的禁忌。最好 post 实际代码,因为它更容易说明到底发生了什么。
对于 C++,您需要的函数可能如下所示:
#include <iostream>
using namespace std;
void calc(unsigned x)
{
unsigned t = 0; // Assume the result to be 0 (zero)
for (i = 1; i <= x; i++) // Continue until i is greater than x
{
t += i; // Accumulate, i.e. t = t +i
}
cout << "sum=" << t << endl; // Print the result
}
int main()
{
calc(10);
return 0;
}
备选方案是:
#include <iostream>
using namespace std;
void calc(unsigned x)
{
cout << "sum=" << (x*(x+1)/2) << endl; // Print the result
}
int main()
{
calc(10);
return 0;
}
这是有效的,因为从 1 到 n 的所有整数的总和是 n*(n+1)/2
我正在努力将 "While" 循环应用于以下问题:设计允许用户输入数字的程序的逻辑。显示从 1 到输入数字的每个数字的总和。
Start
int userNumber;
Declarations
int number = 1
while number <= userNumber
++number
endwhile
output number
Stop
我知道我的代码不正确,因为它只是将初始值加一,直到达到用户号码,从而使输出成为用户号码。我将如何在不写出它们的情况下添加每个后续值,例如用户号是10,所以程序会加上1+2+3+4+5+6+7+8+9+10,输出总数55?
谢谢!
这是一个提示。您需要从用户编号开始倒数到 0。像这样:
int finalNum = 0;
int userNum;
//This is where you need to get the user's number....
while(userNum > 0)
{
finalNum += userNum;
userNum--;
}
//Do whatever you need to finalNum....
编辑:您似乎已经post编辑了伪代码;除非另有说明,否则通常在这里是一个很大的禁忌。最好 post 实际代码,因为它更容易说明到底发生了什么。
对于 C++,您需要的函数可能如下所示:
#include <iostream>
using namespace std;
void calc(unsigned x)
{
unsigned t = 0; // Assume the result to be 0 (zero)
for (i = 1; i <= x; i++) // Continue until i is greater than x
{
t += i; // Accumulate, i.e. t = t +i
}
cout << "sum=" << t << endl; // Print the result
}
int main()
{
calc(10);
return 0;
}
备选方案是:
#include <iostream>
using namespace std;
void calc(unsigned x)
{
cout << "sum=" << (x*(x+1)/2) << endl; // Print the result
}
int main()
{
calc(10);
return 0;
}
这是有效的,因为从 1 到 n 的所有整数的总和是 n*(n+1)/2