繁体   English   中英

我应该如何解决除数程序 C++ 中的计数问题

[英]How should i solve counting problem in my divisor program C++

大家好,我最近开始学习 C++,今天我在计算这个程序中的除数时遇到了问题,我希望我的程序准确计算除数,但是 output 显示奇怪的数字:/

#include <iostream>
using namespace std;
int main(void)
{
    int Lowest;
    int Highest;
    int count = 0;

    cout << "Enter The Lowest Number Of Series: ";
    cin >> Lowest;
    cout << "Enter The Highest Number Of Series: ";
    cin >> Highest;

    cout << "\n Number -> Divisors ((count)) \n";

    for (int i = Lowest; i <= Highest; i++)
    {
        cout << " " << i << " ->";
        for (int j = 1; j <= i; j++)
        {
            if (i % j == 0)
            {
                count++;                                                              // WTF 
                cout << " " << j;
            }
        }
        cout << " (( count:" << count << " )) " << endl;
    }
    return 0;
}

例如,Lower=1 到 Highest=10 的输出如下所示:

Enter The Lowest Number Of Series: 1
Enter The Highest Number Of Series: 10

Number -> Divisors ((count))
 1 -> 1 (( count:1 ))
 2 -> 1 2 (( count:3 ))
 3 -> 1 3 (( count:5 ))
 4 -> 1 2 4 (( count:8 ))
 5 -> 1 5 (( count:10 ))
 6 -> 1 2 3 6 (( count:14 ))
 7 -> 1 7 (( count:16 ))
 8 -> 1 2 4 8 (( count:20 ))
 9 -> 1 3 9 (( count:23 ))
 10 -> 1 2 5 10 (( count:27 ))

你们有什么想法吗?

正如@cigien 的评论所指出的,您的count变量永远不会重置为零,因此它只会不断增加。 在外循环的每次迭代之间重置它。 更好的是,将声明移动到最近的使用它的地方:

#include <iostream>
using std::cin;
using std::cout;  // only using what you need

int main()
{
    int Lowest;
    int Highest;

    cout << "Enter The Lowest Number Of Series: ";
    cin >> Lowest;
    cout << "Enter The Highest Number Of Series: ";
    cin >> Highest;

    cout << "\n Number -> Divisors ((count)) \n";

    for (int i = Lowest; i <= Highest; i++)
    {
        int count = 0;  // <-- initialize to zero on every pass
        cout << " " << i << " ->";
        for (int j = 1; j <= i; j++)
        {
            if (i % j == 0)
            {
                count++;
                cout << " " << j;
            }
        }
        cout << " (( count:" << count << " )) \n";
    }
    return 0;
}

暂无
暂无

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

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