c++ - 我在这个程序中收到“退出,浮点异常”的错误,你能解释一下并给我新代码,为什么会这样?
问题描述
我在这个程序中收到“退出,浮点异常”的错误,你能解释一下并给我新代码,为什么会这样?
这段代码实际在做什么的问题如下:编写一个程序来实现一个多线程解决方案,以确定给定的数字是否是一个完美的数字。N是一个完美数,如果它的所有因数之和(不包括它自己)是N;示例是 6 和 28。输入是整数 N。如果数字是完美数,则输出为真,否则为假。主程序将从命令行读取数字 N 和 P。主进程将产生一组 P 线程。从 1 到 N 的数字将在这些线程之间进行分区,这样两个线程就不会在名称编号上工作。对于该集合中的每个数字,线程将确定该数字是否为 N 的因数。如果是,则将该数字添加到存储 N 的因数的共享缓冲区中。父进程等待所有线程完成。在此处使用适当的同步原语。然后,父母将确定输入的数字是否完美,即 N 是否是其所有因素的总和,然后进行相应的报告。(注意:您可以通过将搜索的数字限制在 1 到 N 的平方根来加快计算速度。)
#include <iostream>
#include <string>
#include <thread>
#include <vector>
using namespace std;
vector<int> factors; // global variable to store factors
void fun(int start, int end, int n) {
// this method adds the factor of n
// between numbers start to end to the vector
int i, s = 0;
for(i = start; i <= end; i++) {
if(n % i == 0) {
factors.push_back(i); // adding factors to the vector
}
}
}
int main(int argc, char** argv) {
int i, n, p, half, sum = 0;
if(argc >= 2) {
n = stoi(argv[1]); // reading N from command line
p = stoi(argv[2]); // reading P from command line
}
half = n / 2; // store half of N for fast computation
int parts = half / p; // part size to divide numbers to different threads
int count = 0;
thread th[p]; // making p threads
for(i = 0; i < p - 1; i++) {
th[i] = thread(fun, count * parts + 1, (count + 1) * parts,
n); // threads from 1 to p-1
count++;
}
th[p - 1] = thread(fun, count * parts + 1, half, n); // last thread
for(i = 0; i < p; i++) {
th[i].join(); // joining all threads before proceeding ahead
}
for(i = 0; i < factors.size(); i++) {
sum += factors[i]; // adding all the factors inside the vector in variable
// sum
}
if(sum == n)
cout << n << " is perfect number\n";`
else
cout << n << " is not perfect number\n";
return 0;
}
解决方案
推荐阅读
- python - 自动输入程序
- mongodb - 优化 MongoDB 聚合查询性能
- reactjs - 在 React 中将类绑定到 Material-Table 数据
- c# - 跨多个项目的核心代码的 Unity 子模块
- php - 如何处理多个客户端套接字?使用 PHP socket_select()
- node.js - 按已删除列扫描或查询数据
- haskell - 为什么我的模式在两边都阻止了错误?
- nhibernate - 在 NHibernate 中的组件内建模列表的最佳方法
- nearprotocol - 如何使用 AssemblyScript 在 NEAR 合约上使用 PersistentUnorderedMap?PersistentUnorderedMap 初始化后没有出现在 Contract Storage 中
- android-vectordrawable - Android Vector Drawable - 带弯角的六边形