c++ - 代码在不使用 cout 时卡住并且不适用于某些数字
问题描述
代码的作用:
这段代码的作用是给定所需的素数数量,从 2 开始,它用这些素数组成一个数组。找到素数它的作用是将一个可能是素数的数字除以该数组上的每个数字,如果每个除法中的余数不为0,则表示这是一个素数,但如果不是余数之一是 0,这意味着它不是素数,所以我们继续搜索它之后的下一个数字。
问题:
1.如果删除,在第46行
cout << ".";
程序卡住了。这就像薛定谔猫,因为如果我不使用 cout,我不知道它卡在代码的哪一部分,如果我使用 cout,它就可以工作
2.当你给数字,比如1000000,程序退出,代码:-1073741571,这是为什么?好吧,在第 49 行中,完成了 0/n 的除法;这里有什么奇怪的?好吧,当想要的素数为 1000000 和搜索 1000 个第一个素数时为 1000 时,这部分代码在理论上是相同的,并且至少在找到前 1000 个素数时它应该是相同的
最后,代码:
#include<iostream>
using namespace std;
unsigned int primesWanted;
unsigned int possiblePrime=3; //We are going to start searching on the 3
unsigned int primesFound = 1; //We start asigning 2 because later we declare that we have one prime found, the 2
int main(int argc, char* argv[])
{
cout <<"Number of primes wanted?:"<< endl << "=========================" << endl;
cin >> primesWanted;
cout << endl << "========================="<< endl; //the ======== is just for decoration
int primes[primesWanted]; // this is an array that contains all primes found
primes[0]= 2; // We asign the 2 as the first prime found
while(primesFound < primesWanted) // this will be executed until all primes wanted are found
{
cout<< "."; //if you delete this, it doesnt work i dont know why
for (unsigned int i = 1; i <= primesFound; i++)
{
if(possiblePrime % primes[i-1]) //if the number that we are searching remainder is 0 when dividing by a prime, thats mean that could be a prime
{
if(i == primesFound) //if i is equal as the number of primes found, that means that that possiblePrime is a prime
{
primes[primesFound] = possiblePrime; //we add it to the prime list
primesFound++; //we add one because we have added on prime to the list
}
}
else
{
break; //if the number that we are searching remainder is 0 when dividing by a prime, thats mean that is not a prime
}
}
possiblePrime++; //we continue to the next number to search
}
//we print the primes array
cout <<endl << "========================="<< endl;
for (unsigned int i = 0; i < primesFound; i++)
{
cout <<primes[i] << ", ";
}
cout <<endl << "========================="<< endl;
system("pause");
return 0;
}
解决方案
你不能cin >> primesWanted;
,因为它是数组的大小,必须是 const。即使没有cout<<".";
这种代码也可以完美运行的其他方式不可能成为问题
推荐阅读
- network-programming - 从 NFQUEUE 返回 netfilter 后如何强制重新路由数据包
- image - “无法转换:'_Uri'的实例”在flutter web上的cloud firestore最新版本上上传图像时出错
- database - 关于搜索引擎自动完成的问题
- ios - Firebase 可选崩溃未正确显示
- c# - TCP 套接字客户端\服务器请求响应
- c# - 如何根据 xamarin.forms 中的条件更改条目的线条颜色
- r - 在 R 中使用 for 循环保存数据帧
- arrays - 将 ORDS 连接到 Angular
- android - 如何在 Firebase 数据库 android 中增加价值
- asp.net-core - 使用 Swashbuckle 和 NSwag 的 WebApi 中的代码生成复杂输入参数