Sar*_*_Xx 3 c++ loops function
我需要找到两个数字之间的素数之和,比如x1和x2,但是我无法检测到什么是错误的?例如,如果我输入3和9我会得到15但我得到133!
#include <iostream>
using namespace std;
int prime(int n1, int n2)
{
int count =0;
bool prime = true;
for (n1; n1 < n2; n1++)
{
for (int i = 2; i < n1; i++)
{
if (n1 % i == 0) {
prime = false;
continue;
}
else
count++;
}
}
return count;
}
int main()
{
int n1, n2;
cout << " Enter values for n1 and n2 (n1 must be smaller than n2): ";
cin >> n1>>n2;
cout << " Sum of prime numbers from " << n1 << " and till " << n2 << " inclusively : " << prime(n1, n2) << endl;
system("pause");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
你的主要功能是不合适的.这应该是这样的.
int prime(int n1, int n2) {
int sum = 0;
for (n1; n1 < n2; n1++) {
bool prime = true;
for (int i = 2; i < n1; i++) {
if (n1 % i == 0) {
prime = false;
break;
}
}
if( prime ) { // current n1 is prime
sum = sum + n1;
}
}
return sum;
}
Run Code Online (Sandbox Code Playgroud)
如果你的n1是素数,你不会添加任何东西.