【问题标题】:for loop not incrementing through table of array C++ [closed]for循环不通过数组C++表递增[关闭]
【发布时间】:2018-02-25 22:19:31
【问题描述】:

我已经单独测试了我的数组,以确保它可以正常工作并保存所有值,但由于某种原因,当我通过我的 for 循环运行它时,它只会在 3 行和 3 列中打印出 10.95 我没有不明白为什么它没有从我的表中提取其余的值。

这是作业:

编写、编译并运行一个 C++ 程序,将以下值输入到名为 prices 的数组中:10.95、16.32、12.15、8.22、15.98、26.22、13.54、6.45 和 17.59程序以 3 行 3 列的形式显示值。

这是我写的代码:

#include <iostream>
#include <iomanip>
using namespace std;

const int COLS = 3;
const int ROWS = 3;

int main()
{
    const int num_items = 9;
    float prices[num_items];

    cout << "Enter the prices of your " << num_items << " items: ";
    cin >> prices[0];
    cin >> prices[1];
    cin >> prices[2];
    cin >> prices[3];
    cin >> prices[4];
    cin >> prices[5];
    cin >> prices[6];
    cin >> prices[7];
    cin >> prices[8];

    float table[ROWS][COLS] = {{prices[0], prices[1], prices[2]},
                                {prices[3], prices[4], prices[5]},
                                {prices[6], prices[7], prices[8]}};

    cout << "The prices you have entered are:\n";

    for (int x = 0; x < ROWS; x++)
    {
        for (int y = 0; y < COLS; y++)
        {
            cout << setw(6) << table[ROWS][COLS] << " ";
        }
        cout << endl;
    }
    return0;
}

【问题讨论】:

  • table[ROWS][COLS] --> table[x][y]。投票结束是一个错字。
  • 是时候了解for,以免您的程序在所有重复重复的重压下崩溃。更少的代码行通常意味着错误更明显,因为隐藏的地方更少。
  • 考虑报告更多信息...如何更改'cout

标签: c++ arrays for-loop


【解决方案1】:
cout << setw(6) << table[ROWS][COLS] << " ";

应该是

cout << setw(6) << table[x][y] << " ";

【讨论】:

  • 非常感谢,我已经看了将近 20 分钟,试图找出原因
  • 我已经看了大约 20 分钟,试图找出原因 我的建议是学习如何使用调试器。我的意思是单步执行代码,查看每一步的变量。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-21
  • 1970-01-01
  • 2014-06-11
  • 2018-07-15
  • 1970-01-01
相关资源
最近更新 更多