【问题标题】:C++ "While" LoopC++“While”循环
【发布时间】:2015-06-29 00:52:39
【问题描述】:

我正在努力将“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?

谢谢!

【问题讨论】:

  • 只需将它们累加为一个总和。这有什么难的?
  • 您的代码似乎不是 C++,您确定您正确标记了问题吗?此外,您没有从用户那里收到数字,也没有累积,只计算 1 和给定数字之间的数字。
  • @Guvante,我删除了 C++ 标签。我正在使用 C++ 编程,但这只是一些粗略的伪代码,以帮助解释我目前的想法(因此出现错误)。
  • @Lee Daniel Crocker,不要无礼,假设我应该自动知道如何积累。
  • @Anonymous - 如果您正在寻找 c++ 解决方案,请不要删除 c++ 标签。 :) 但是你应该说:这个伪代码,我怎么能在 C++ 中做到这一点。

标签: c++ while-loop


【解决方案1】:

对于 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

【讨论】:

    【解决方案2】:

    这里有一个提示。您需要从用户数开始倒数到 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....
    

    编辑:您似乎发布了伪代码;除非另有说明,否则这里通常是一个很大的禁忌。最好发布实际代码,因为这样更容易判断到底发生了什么。

    【讨论】:

    • 感谢您的帮助。我认为这就是我试图做到的方式。对伪代码感到抱歉。我不记得读过任何警告过它的东西。
    猜你喜欢
    • 2013-02-08
    • 1970-01-01
    • 2018-05-09
    • 2013-04-07
    • 1970-01-01
    • 2016-08-27
    • 2012-11-11
    • 2014-04-01
    • 2016-09-23
    相关资源
    最近更新 更多