创建一个函数,将数组作为具有适当行和列的表打印到屏幕。使用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返回1退出状态错误,你能帮忙吗?
答案 0 :(得分:1)
您的打印功能的定义和声明是不同的。
答案 1 :(得分:0)
更改print()
功能的声明。
void print(int arr[ROWS][COLS]);
到
void print(const int arr[ROWS][COLS]);