我想从cin中读取矩阵,使用函数,然后将矩阵返回到main。
这是我的代码:
的main.cpp
#include <iostream>
#include <windows.h>
#include <vector>
#include "mymath.h"
using namespace std;
int main(){
vector<vector<double>> matrix_read();
Sleep(60000);
return 0;
}
mymath.h
#pragma once
#ifndef MYMATH_H
#define MYMATH_H
vector<vector<double>> matrix_read();
#endif
mymath.cpp
#include "mymath.h"
#include <vector>
#include <iostream>
using namespace std;
vector<vector<double>> matrix_read() {
cout << "How big is the quadratic matrix A?\n";
int n;
//row&column size A
cin >> n;
vector<vector<double>> A(n, vector<double>(n));
//fill matrix A
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> A[i][j];
}
}
//control matrix A:
cout << "Please be sure this is the correct Matrix A: \n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << A[i][j] << " ";
}
cout << endl;
}
return A;
}
供参考: Return multidimensional vector from function for use in main, how to use correctly?
我的错误是什么?
错误列表意味着存在重大错误。谢谢您的帮助。请温柔,新手在这里。
答案 0 :(得分:1)
如果您在include指令之前没有vector
,则需要在标头中为std::vector
添加前缀using namespace std;
。无论如何,在标题中添加std::
是一种很好的做法。
主要应该是
int main(){
vector<vector<double>> matrix = matrix_read();
Sleep(60000);
return 0;
}
即。将对象matrix
设置为函数的返回值。否则,您将在main函数中为matrix_read
定义另一个原型。
答案 1 :(得分:0)
MaximilianMatthé是对的。这是工作代码:
<强> mymath.h 强>
#pragma once
#include <vector>
#include <iostream>
std::vector<std::vector<double>> matrix_read();
<强> mymath.cpp 强>
#include "mymath.h"
std::vector<std::vector<double>> matrix_read() {
std::cout << "How big is the quadratic matrix A?\n";
int n;
//row&column size A
std::cin >> n;
std::vector<std::vector<double>> A(n, std::vector<double>(n));
//fill matrix A
int j = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
std::cout << "Please enter the value for A" << "[" << i + 1 << "]" << "[" << j + 1 << "]\n";
std::cin >> A[i][j];
}
}
//control matrix A:
std::cout << "Please be sure this is the correct Matrix A: \n\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
std::cout << A[i][j] << " ";
}
std::cout << std::endl;
}
return A;
}
<强>的main.cpp 强>
#include <windows.h>
#include "mymath.h"
int main() {
std::vector<std::vector<double>> A = matrix_read();
Sleep(60000);
return 0;
}