C++函数和数组作业

标签 c++ arrays function

创建一个函数,将数组作为具有适当行和列的表格打印到屏幕上。使用 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/

相关文章:

c++ - 对象的析构函数导致崩溃

c++ - 为什么结果是0?

javascript - 遍历 JSON 并将数组更改为字符串

javascript - 箭头函数中的三元运算符

r - 在R中的数据点之上绘制函数

c++ - 使 Boost.Spirit 解析器跳过所有空格

c++ - 从命令行定义源文件的宏

php - PHP 中从多维数组获取平面数组的内置方法

python - 如何使用 numpy.savez 将带有子数组的数组保存到单独的 .npy 文件中

c++ - 在 C++ 中有什么方法可以确保在编译时没有在任何地方使用非模板函数?