注册 登录
编程论坛 C++教室

实现效果和想象中的不一致,求大神指点【二维数组+for嵌套循环】

a75692074 发布于 2018-12-31 20:44, 2866 次点击
程序代码:

#include <iostream>
using namespace std;
const int Cities = 5;
const int Years = 4;

int main()
{
    const char * cities[Cities] = // array of pointers
    {                              // to 5 strings
        "Gribble City",
        "Gribbletown",
        "New Gribble",
        "Gribble vista"
    };

    int maxtemps[Years][Cities] = // 2-D array
    {
        {96, 100, 87, 101, 105}, // values for maxtemps[0]
        {96, 98, 91, 107, 104}, // values for maxtemps[1]
        {97, 101, 93, 108, 107}, // values for maxtemps[2]
        {98, 103, 95, 109, 108} // values for maxtemps[3]
    };
   
    cout << "Maximum temperatures for 2008 - 2011\n\n";
    for (int city = 0; city < Cities; ++city)
    {
        cout << cities[city] << ":\t";
        for (int year = 0; year < Years; ++year)
            cout << maxtemps[year][city] << "\t";
        cout << endl;
    }
        // cin.get();
    return 0;
}


想象中的实现效果:
Maximum temperatures for 2008 - 2011

Gribble City:96
Gribbletown: 98
New Gribble: 93
Gribble vista:109
. . .
(省略的大神们应该能知道我想的是什么吧!)


现实中的实现效果:
Maximum temperatures for 2008 - 2011

Gribble City: 96  100  87  101   105
Gribbletown:  96  98   91  107   104
New Gribble:  97  101  93  108   107
Gribble vista:98  103  95  109   108

(实现效果是很整齐的噢)

求大神指点一下为什么实现效果是这样!
感谢!!!

[此贴子已经被作者于2018-12-31 20:48编辑过]

6 回复
#2
rohalloway2018-12-31 21:46
在我这里是整齐的没有问题

你也可以试试cout << cities[city] << ":\t\t";

或者用函数补空格应该是最齐的
#3
a756920742018-12-31 23:42
回复 2楼 rohalloway
你没看懂。
#4
a756920742018-12-31 23:43
回复 楼主 a75692074
我问的是为什么实现效果和我想象中的不一样
#5
林月儿2019-01-01 00:08
可能内循环要加判断吧,比如year==city
#6
ZJYTY2019-01-02 17:35
for (int city = 0; city < Cities-1; ++city)
    {
        cout << cities[city] << ":\t";
        for (int year = 0; year < Years; ++year)
        {
            if (city == year)
                cout << maxtemps[year][city] << "\t";
        }
        cout << endl;
    }

/*
至于你所贴出的现实中的实现效果,可以分析一下自己的程序。
1:const char * cities[Cities]中只有四个元素,下面操作到了第五个,应该会崩溃。
2:内层循环输出的是一列,并不是一行。

你确认自己运行的代码是这样的?
*/
#7
a756920742019-01-12 22:16
回复 6楼 ZJYTY
是的,谢谢啦
1