c++ - 如何在 C++ 中部分填充数组
问题描述
我正在尝试部分填充数组,但是在运行时,程序继续运行超过用户给出的限制。还有另一种方法来部分填充数组吗?
最初的 NUM_ROWS 和 NUM_COLUMNS 常量是占位符,直到程序工作
#include <iostream> // Input and output
#include <iomanip> // Input manipulator
#include <array>
using namespace std;
// Number used to initialize an array
const int NUM_ROWS = 10;
const int NUM_COLS = 10;
int userFilledArray[NUM_ROWS][NUM_COLS];
int row; // Amount of rows the user will fill
int col; // Amount of columns the user will fill
int main()
{
int num; // Number that is placed in a specific row and column
int total; // Total of every integer in the array
int average; // Average of every integer in the array
int rowTotal; // Total of every integer in a specific row
int colTotal; // Total of every integer in a specific column
int highestInRow;
int lowestInRow;
// Asks the user to enter the number of rows they would like to fill
cout << "How many rows in the array would you like to fill? (Between 1 - 10)" << endl;
cin >> row;
// Asks the user to enter a number between 1-10 if the user enters a character or integers not between 1-10
while (row < 0 || row > 10)
{
cout << "Please enter a number between 1-10" << endl;
cin >> row;
}
// Asks the user to enter the number of columns they would like to fill
cout << "How many columns in the array would you like to fill? (Between 1 - 10)" << endl;
cin >> col;
// Asks the user to enter a number between 1-10 if the user enters a character or integers not between 0-10
while (col < 0 || col > 10)
{
cout << "Please enter a number between 1-10" << endl;
cin >> col;
}
// Now the user will fill the array with as many numbers needed
for (int i = 0; i < row; i++) // WARNING!!! NOT WORKING
{
for (int j = 0; i < col; j++) // WARNING!!! NOT WORKING
{
cout << "Enter a number for row " << i << " and column " << j << endl;
cin >> num;
userFilledArray[i][j] = num;
}
}
total = getTotal(userFilledArray);
cout << total << endl;
}
这是无法正常工作的区域
// Now the user will fill the array with as many numbers needed
for (int i = 0; i < row; i++) // WARNING!!! NOT WORKING
{
for (int j = 0; i < col; j++) // WARNING!!! NOT WORKING
{
cout << "Enter a number for row " << i << " and column " << j << endl;
cin >> num;
userFilledArray[i][j] = num;
}
}
}
解决方案
这是您有问题的行:
for (int j = 0; i < col; j++) // WARNING!!! NOT WORKING
它还说明了为什么单字母变量名会导致错误。您从前一个 for 循环中剪切并粘贴了它,并且您没有更改 variable 的每个实例i
。
推荐阅读
- laravel-5 - 对预检请求的响应未通过?
- javascript - 在画布上居中图像并调整画布宽度的 50%
- c++ - C++(线性搜索和排序)
- reporting-services - 尝试打印任何报告时出现错误“报告数据集执行期间发生错误”
- html - 围绕列的样式表
- java - Docker compose mysql 容器在依赖它的应用程序之后运行
- tinymce - WYSIWYG 编辑器在 mac Prestashop1.6 上消失了
- java - 安装后如何永远运行应用程序?
- ios - Firebase 应用内消息按钮操作不起作用
- oracle - 如何在行之间找到oracle中常见的最长子字符串?