我试图找到两个给定数字之间的所有素数并将素数相加。
我有这个循环可以正确检测素数。
但是,由于某种原因,我不知道如何对所有素数求和。
int a,b,i,j,sum=0;
do
{ cout << "Enter a number: ";
cin >> a;
if (a < 4 || a > 1000000)
{ cout << "Input must be between 4 and 1000000 inclusive." << endl;
}
}while (a < 4 || a > 1000000);
do
{ cout << "Enter a second number: ";
cin >> b;
if (b < 4 || b > 1000000)
{ cout << "Input must be between 4 and 1000000 inclusive." << endl;
}
}while (b < 4 || b > 1000000);
if (a > b)
{ int hold;
hold = b;
b = a;
a = hold;
}
cout << "The prime numbers between " << a << " and " << b << " inclusive are: " << endl;
//int sum;
for (i = a; i <= b; i++)
{
for (j = 2; j <= i; j++) // Changed the < to <=, and got rid of semicolon
{
if (!(i%j)&&(i!=j)) break;
if (j==i)
{
cout << i << endl;
sum += i;
cout << sum ;
}
}
}
该变量sum
给了我垃圾结果。