我的循环超时而不显示结果

时间:2018-05-24 20:50:39

标签: c++ loops

我正在尝试学习while循环,并且我编写了一个代码,用于将三位数下的给定数字的所有倍数相加,所以如果输入5则会添加5,10,15,20,25 ...等。它们显示了这些数字的总和。我认为我的代码编写得非常好,但是就像标题所提到的那样,它会陷入循环并且不会显示结果。

这是我的代码:

#include <iostream>
using namespace std;

double getnum()
{
    double num;
    cout << "What multiples are we adding? ";
    cin >> num;

    return num;
}

double calculate(double num)
{
    double cal;
    while (num < 100) ;
    {
        int cal = num;
        num++;
    }

    return cal;
}

double display(double num, double cal)
{
    cout << "the sum of multiples of " << num << " less than 100 are: "
         << cal << endl;
}

int main()
{

    double num = getnum();
    double cal = calculate(num);

    display(num, cal);

    return 0;
}

2 个答案:

答案 0 :(得分:2)

在这种情况下,for循环比while循环要好得多。 while循环更适合“做一件事直到满足条件”,而for更适合“做事X次”。

您的代码中存在一些错误,例如

double calculate(double num)
{
    double cal; // <--- you return this
    while (num < 100) ; <---- this ; shouldn't be there and causes the loop to never terminate
    {
        int cal = num; <-- you just assign cal here? 
        num++;
    }

    return cal; <--- you return a variable that is never modified
}

希望这个片段能让你前进:

#include <iostream>

int main()
{

    int num = 0;
    std::cout << "What multiples are we adding? ";
    std::cin >> num;

    int sum = 0;
    for(int i = 1; i < 100; ++i)
    {
        if( i % num == 0) // modulus division, no remainder
        {
            std::cout << "Adding " << i << std::endl;
            sum += i;
        }
    }

    std::cout << "Sum = " << sum<< std::endl;;
    return 0;
}

输出:

./a.out
What multiples are we adding? 5
Adding 5
Adding 10
Adding 15
Adding 20
Adding 25
Adding 30
Adding 35
Adding 40
Adding 45
Adding 50
Adding 55
Adding 60
Adding 65
Adding 70
Adding 75
Adding 80
Adding 85
Adding 90
Adding 95
Sum = 950

将来发布更易读的代码会更有帮助,特别是带注释的代码!

答案 1 :(得分:1)

您陷入循环的主要原因是您不应在;循环后使用while。即使您删除了;,代码的输出也不会提供您期望的结果。您可以使用以下代码替代@Chris提供的代码

#include <iostream>
using namespace std;

double getnum()
{
    double num;
    cout << "What multiples are we adding? ";
    cin >> num;
    return num;
}

double calculate(double num)
{
    double cal = 0;
    int inc = num;
    while (num < 100)
    {
        cal += num;
        num += inc;
    }
    return cal;
}

double display(double num, double cal)
{
    cout << "Sum of multiples of " << num << " less than 100 are: ";
    cout << cal << endl;
}

int main()
{
    double num = getnum();
    double cal = calculate(num);
    display(num, cal);
    return 0;
}