【问题标题】:How do you fix the array to make it right?您如何修复阵列以使其正确?
【发布时间】:2020-01-11 22:50:44
【问题描述】:
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    /* Hello! I didn't know if we had to use functions, because the assignment didn't say. Please tell me if you would like to resubmit and add functions.*/
    int num1=1, num2=2, num3=3, num4=4, num5=5, num6=6, i;
    for (i=1; i<=6; i++) {
        if (num1=i) {
            num1=num1;
        }
        else if (num2=i) {
            num2=1;
            num2=num2*2;
        }
        else if (num3=i) {
            num3=1;
            num3=num2*2*2;
        }
        else if (num4=i) {
            num4=1;
            num4=num2*2*2*2;
        }
        else if (num5=i) {
            num5=1;
            num5=num2*2*2*2*2;
        }
        else if (num6=i) {
            num6=1;
            num6=num2*2*2*2*2*2;
        }
    }        

    int array[2][6] = {{num1, num2, num3, num4, num5, num6},{0, 1, 2, 3, 4, 5}};
    for (int row=0; row<2; row++) {

        for (int column=0; column<6; column++) {
            cout << array[2][6] << " ";
        }
        cout<<endl;
    }

    cout<<num1<<" "<<num2<<" "<<num3<<" "<<num4<<" "<<num5<<" "<<num6<<endl;

    return 0;
}

这应该是返回

1 2 4 8 16 32
0 1 2 3 4 5
1 2 4 16 32

目前,它返回一些非常不同的东西......我该怎么办?

另外,我知道这是一种非常低效的方法,所以如果你有更好的方法,我也愿意接受。在这个数组中,2^i 只是存储在第 i 个位置。

【问题讨论】:

  • cout &lt;&lt; array[2][6] &lt;&lt; " ";??这在逻辑上是错误的,也是未定义的行为
  • if (num1=i) 应该是 if (num1==i)。其他地方也一样。
  • cout &lt;&lt; array[row][column] 而不是 cout &lt;&lt; array[2][6]

标签: c++ arrays multidimensional-array


【解决方案1】:

您应该使用num1==i 而不是num1=i。您在数组 [2] [6] 中只有两行,并且您想打印 3 行,因此您应该在数组 [2][6] 中添加另一行 {num1, num2, num3, num4, num5, num6}。将cout &lt;&lt; array[2][6] &lt;&lt; " "; 替换为 cout &lt;&lt; array[row][column] &lt;&lt; " ";

【讨论】:

    猜你喜欢
    • 2010-11-12
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-17
    • 1970-01-01
    相关资源
    最近更新 更多