使用for循环在2D Float数组上输入值

时间:2019-08-06 17:27:40

标签: c arrays loops for-loop

我正在尝试制作一个2列和2行的2D数组。第一列是使用scanf输入的半径,而第二列是依赖于第一列的面积。

我已经尝试使它们脱离循环(手动输入),然后立即输出它们,但是不知何故,只有最后一个输入和第一个输入才正确

dict

输入8和3时,我希望它是输出

您的圈子:         800万200.960000         3.000000 28.260000

但是我得到了这个

您的圈子:         8.000000 0.000000         0.000000 28.260000

格式为

您的圈子:[0] [0] [0] [1] [1] [0] [1] [1]

2 个答案:

答案 0 :(得分:1)

更改此:

for(int x = 0; x <= circlerow; x++)

对此:

for(int x = 0; x < circlerow; x++)

因为数组索引从0开始,以数组大小-1结束。

类似地,您将执行for(int j = 0; j < circlecol; j++)

通常,如果数组声明为:

array[rows][cols]

则其尺寸为rows x colsarray[0][0]是第一行和第一列中的元素,array[rows - 1][cols - 1]是最后一列和最后一行中的元素。


最小的完整示例:

#include <stdio.h>

#define circlecol 1
#define circlerow 1

int main(void) {
  float circles[circlerow][circlecol];
  for(int x = 0; x < circlerow; x++) {
    scanf("%f", &circles[x][0]);
    circles[x][1] = 3.14*circles[x][0]*circles[x][0];
  }

  for(int i = 0; i < circlerow; i++)
    for(int j = 0; j < circlecol; j++)
      printf("%f", circles[i][j]);
  return 0;
}

答案 1 :(得分:0)

此数组

float circles[circlerow][circlecol];
实际上

被声明为

float circles[1][1];

也就是说,它只有一行和一列,只能使用表达式circle[0][0]来访问。

似乎您的意思是以下

#define circlecol 2
#define circlerow 2

int main( void ) {
    float circles[circlerow][circlecol];
    for(int x = 0; x < circlerow; x++) {
        scanf("%f", &circles[x][0]);
        circles[x][1] = 3.14*circles[x][0]*circles[x][0];
    }
}

即数组应具有两行两列。

相关问题