C ++汇总了以前打印过的列表中的数字

时间:2017-10-10 18:48:31

标签: c++

我编写了一个程序来提示用户输入两个数字,然后确定两个初始值之间范围内的所有素数。我想总结一下找到的素数。有没有人有任何指针?我将包括我当前的,不正确的,尝试使这项工作。谢谢你的帮助。

编辑 - 完整代码现在在下面。

#include <iostream>

using namespace std;

int main()
{
    int smallernumber, largernumber, counter, i, IsPrime;
    int sum = 0;


    cout << "Welcome to the Prime Number calculator!  This program will"
        "\ncalculate prime numbers between two values that you'll enter.\n Please enter the the smaller of two values: ";
    cin >> smallernumber;
    cout << "\nPlease enter the larger value ";
    cin >> largernumber;

    for (counter = 2; counter <= largernumber; counter++) {
        IsPrime = 0;

        for (i = 2; i < counter; i++) {

            if (counter % i == 0) {
                IsPrime = 1;


            }
        }

        if (IsPrime == 0 && counter != 1)

            cout << counter << " ";


    }
    for (counter = 2; IsPrime == 0 && counter != 1; counter++) {
        sum += counter;
    }
    cout << "\nthe sum of the prime numbers is: " << sum << endl;

}

2 个答案:

答案 0 :(得分:1)

sum += counter移到if子句中:

if (IsPrime == 0 && counter != 1) {
    sum += counter;
    cout << counter << " ";
}

答案 1 :(得分:0)

你想要的代码我想是@ manni66和@Daniel Trugman。

{
int smallernumber, largernumber, counter, i, IsPrime;
int sum = 0;


std::cout << "Welcome to the Prime Number calculator!  This program will"
    "\n calculate prime numbers between two values that you'll enter.\n Please enter the the smaller of two values: ";
std::cin >> smallernumber;
std::cout << "\n Please enter the larger value ";
std::cin >> largernumber;

for (counter = smallernumber; counter <= largernumber; counter++) 
{
    IsPrime = 0;

    for (i = 2; i < counter; i++) {
        if (counter % i == 0) {
            IsPrime = 1;
        }
    }

    if (IsPrime == 0 && counter != 1)
    {
        std::cout << counter << " ";
        sum += counter;
    }

}
std::cout << "\nthe sum of the prime numbers is: " << sum << "\n";
}