随机数大于 1000 的矩阵乘法
Matrix multiplication with random numbers larger than 1000
我正在尝试让两个随机生成的数字矩阵相乘,但我不断遇到分割错误和 idk 如何正确分配内存。
对此的任何帮助都会很棒
这是代码
#include<iostream>
#include<iomanip>
#include<stdlib.h>
#include<stdio.h>
#include<ctime>
using namespace std;
int main()
{
srand (1023);
int a[1000][1000], b[1000][1000], mult[1000][1000], r1, c1, r2, c2, i, j, k;
cout << "Enter rows and columns for first matrix: ";
cin >> r1 >> c1;
cout << "Enter rows and columns for second matrix: ";
cin >> r2 >> c2;
while (c1!=r2)
{
cout << "Error! column of first matrix not equal to row of second.";
}
cout << endl << endl;
for(i=0; i<r1; ++i)
for(j=0; j<c1; ++j)
{
cout<<"mult["<<i<<"]["<<j<<"]: "<<rand()%9+1<<" "; //random matrix 1
}
cout << endl<< endl;
for(i=0; i<r2; ++i)
for(j=0; j<c2; ++j)
{
cout<<"mult["<<i<<"]["<<j<<"]: "<<rand()%9+1<<" "; //random matrix 2
}
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
{
mult[i][j]=rand()%9+1;
}
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
for(k=0; k<c1; ++k)
{
mult[i][j]+=a[i][k]*b[k][j]; //matrix multiplication
}
cout << endl << "Output Matrix: " << endl;
clock_t begin = clock();
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
cout << " " << mult[i][j];
if(j==c2)
cout << endl;
clock_t end = clock();
double elapsed_secs = double(end-begin)*100;
cout<<"Elapsed Time: "<<elapsed_secs<<" millisecondsn";
return 0;
}
您正在尝试在当前堆栈中创建超过 11 MB。
数组[1000][1000] = 4 * 1000 * 1000 字节 = 4000000
您仅为 3 个数组总共创建了 12000000 字节。
尝试减小数组的大小(或)获取矩阵的大小,并尝试使用 new 在堆中创建数组。
检查您的堆栈大小,它应该是 8 MB
ulimit -a | grep stack
这就是你对堆的做法,因为你想要 1000 到 5000
int** a = new int*[r1];
for(int i = 0; i < r1; ++i)
{
a[i] = new int[c1];
}
a[0][0] = 10;
std::cout << a[0][0] << std::endl;
// Delete all the columns
for(int i = 0; i < r1; ++i)
delete[] a[i];
delete []a ;
还要确保将值添加到 a[][] 和 b[][],现在您只需执行 cout 并打印前 2 个 for 循环中的值,我想这些值应该在 a[][] 和 b[][] 中
相关文章:
- 大于65535的C++数组[size]引发不一致的溢出
- 查找最接近的大于当前数字的数字的索引
- 如何找到大于整数的最小数字
- 为什么签名字符可以保存大于 127 的值?
- 如何打印大于"无符号长长"的"std::bitset"的十进制值?
- 如何在C++中写入 1000 个文件时有效地缓冲
- 为什么它总是给我大于 4?
- 如果变量数据包含大于 vector 所有元素的整数,则仅在视觉工作室上接收"矢量下标超出范围"?
- 在向量中查找大于 0(或通常为 k)的最小元素的最佳方法是什么?
- 使用 RapidXML 解析大型 XML(大小大于 65 KB)文件时出现问题
- CStdioFile 不能处理大于 2GB 的文件?
- 为什么 Lisp 中 1000 阶乘的计算如此之快(并显示正确的结果)?
- 当我选择大于 720 的矩阵大小时,程序退出并显示错误代码.可能是什么原因?
- C++大于或等于运算符
- 除数大于两个大因子时的模积
- 如何查找数字大于 5 的数字总和
- 数组大于指定大小(C++)
- 为什么 CSpinButtonCtrl 不能正确处理大于 1000 的数字?
- 随机数大于 1000 的矩阵乘法
- 程序不适用于大于 1000 的数字