我想找出1到100之间的质数。我遇到的问题是当程序将值2赋值给整数类型的变量j时。变量 j 的值不变。有谁知道为什么会这样?
Create a program to find all the prime numbers between 1 and 100.
One way to do this is to write a function that will check if a number is prime (i.e., see if the number can be divided by a prime number smaller than itself) using a vector of primes in order (so that if the vector is called primes, primes[0]==2, primes[1]==3, primes[2]==5, etc.). Then write a loop that goes from 1 to 100, checks each number to see if it is a prime, and stores each prime found in a vector. Write another loop that lists the primes you found. You might check your result by comparing your vector of prime numbers with primes. Consider 2 the first prime.
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<int> primes = { 2 };
for (int i = 2; i <= 100; ++i)
for (int j = 2; j < i; ++j)
if (i % j == 0)
break;
else
primes.push_back(j);
for (int i = 0; i < primes.size(); ++i)
std::cout << primes[i] << ' ';
}
最佳答案
在你最初的实现中有一些错误:
- 您在
primes
vector 中添加元素的时间过早 - 你对素数没有明确的定义
- 您正试图将所有内容放在一个函数中
一些更干净的代码看起来有点像这样:
#include <iostream>
#include <string>
#include <vector>
namespace {
bool isPrime(const std::vector<int> &previousPrimes, int possiblePrime) {
for (auto prevPrime : previousPrimes)
if (possiblePrime % prevPrime == 0)
return false;
return true;
}
}
int main()
{
auto primes = std::vector<int>({2});
for (int i = 3 /*2 is already a prime*/; i <= 100; ++i)
if (isPrime(primes, i))
primes.push_back(i);
for (auto prime : primes)
std::cout << prime << ' ';
std::cout << std::endl;
}
但是,由于这道题看起来像是家庭作业,所以不要盲目照搬,先尝试理解这里使用的所有概念。
关于c++ - 无法为整数类型的变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38917894/