创建一个函数,将数组作为具有适当行和列的表格打印到屏幕上。使用 setw() 确保数字有足够的空间。您可以假设每个数字不超过 3 位。包括行和列标签。
在 main 中,要求用户提供行和列以及一个值(不超过 3 位数字),然后将值放入该行和列的数组中。打印结果并要求用户提供另一个行、列和值。重复直到用户完成。
完成后,计算并打印数组中值的总和。
#include <iostream>
#include <iomanip>
using namespace std;
const int ROWS= 4;
const int COLS = 3;
const int WIDTH = 4;
const char YES = 'y';
int total = 0;
void print(int arr[ROWS][COLS]);
int main()
{
int arr[ROWS][COLS];
char ans = YES;
int val;
for (int r = 0; r < ROWS; r++){
for (int c = 0; c < COLS; c++)
arr[r][c] = 0;}
while (tolower(ans) == YES){
int row = -1;
int col = -1;
cout << "Row? ";
cin >> row;
cout << "Columns? ";
cin >> col;
while (row < 0 || row >=ROWS){
cout << "Only value under " << ROWS << " is accepted, try again: ";
cin >> row;
}
while (col < 0 || col >= COLS){
cout << "Only value under " << COLS << "is accepted, try again: ";
cin >> col;
}
cout << "Value? ";
cin >> val;
arr[row][col] = val;
print(arr);
cout << "Again (y/n)? ";
cin >> ans;
}
for (int r = 0; r < ROWS; r++){
for (int c = 0; c < COLS; c++){
total += arr[r][c];
}
}
cout << "Sum of all values is " << total << endl;
// Print array with labels
// get input from user
// print array again - repeat until user wishes to quit
return 0;
}
void print (const int arr[ROWS][COLS])
{
cout << endl << endl;
for (int i = 0 ; i < COLS; i++)
cout << setw(WIDTH) << i;
cout << endl;
for (int r = 0; r < ROWS; r++)
cout << setw(WIDTH) << r << "|";
for (int r = 0; r < ROWS; r++)
for (int c = 0; c< COLS; c++)
cout << setw(WIDTH) << arr[r][c];
cout << endl << endl;
}
我不知道我哪里做错了,但是当我编译时,我得到了 LD return 1 exit status 错误,你能帮忙吗?
最佳答案
打印函数的定义和声明不同。
关于C++函数和数组作业,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28733207/