简体   繁体   English

在c ++中的for循环中,如何使用

[英]In c++, in a for loop, how do you print out a string once with

What I'm dealing with is a nested for loop that finds perfect numbers. 我正在处理的是一个嵌套的for循环,可以找到完美的数字。 The iterations to find the perfect number came about pretty quickly. 寻找完美数字的迭代过程很快就出现了。 However, I need the output to show a string that says, "perfect number found" and have that happen once. 但是,我需要在输出中显示一个字符串,指出“找到了完美的数字”,并且使该字符串发生一次。 Then on the same line, print out all the perfect numbers. 然后在同一行上,打印出所有理想数字。 So for example, lets say I have two inputs, 1 to 30. 例如,假设我有两个输入,即1到30。

That means that the perfect numbers are 6 and 28. The output should be something like. 这意味着完美的数字是6和28。输出应该类似。

Perfect numbers: 6 28. 完美数字:6 28。

What I'm confused on is how to print out just that string once in the for loop I have created. 我很困惑的是如何在我创建的for循环中仅打印出该字符串。 Here's what I have so far. 到目前为止,这就是我所拥有的。

#include <iostream>

int main()
{
    int a, b;
    std::cin >> a >> b;
    int count = 0;

    for (int i = a; i <= b; i++)
    {
        int sum = 0;
        for (int j = 1; j <= i; j++)
        {
            if (i % j == 0)
            {
                sum += j;
            }
        }
        if (i * 2 == sum)
        {
            std::cout << i << " ";
            count++;
        }
    }
    std::cout << "\n";
    std::cout << "number of perfect numbers found: " << count << std::endl;

    return 0;
}

Why do it "in the for loop"? 为什么要“在for循环中”? Do it before you enter the for loop. 在进入for循环之前执行此操作。

Or, if you want to make sure you found at least one perfect number before committing yourself to printing that string, then on the line where you print out the individual values, instead of: 或者,如果要确保在致力于打印该字符串之前找到至少一个完美的数字,则在打印出各个值的那一行,而不是:

std::cout << i << " ";

just say: 说啊:

std::cout << (count == 0 ? "Perfect numbers: " : "") << i << " ";

you can try something like this and just add the print with the cout 您可以尝试类似的操作,只需添加带有cout的打印

for(i=start; i<=end; i++)
    {
        sum = 0;

        /* Check whether the current number i is Perfect number or not */
        for(j=1; j<i; j++)
        {
            if(i % j == 0)
            {
                sum += j;
            }
        }

        /* If the current number i is Perfect number */
        if(sum == i)
        {
            cout <<i<<" ,";
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM