【问题标题】:Inputting value on 2D Float arrays with for loops使用 for 循环在 2D 浮点数组上输入值
【发布时间】:2019-12-14 07:31:57
【问题描述】:

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

我已经尝试将它们排除在循环之外(手动输入),然后立即输出它们,但不知何故只有最后一个和第一个输入是正确的

#define circlecol 1
#define circlerow 1

int main() {
    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];
    }`

输入 8 和 3 我希望这是输出

你的圈子: 8.000000 200.960000 3.000000 28.260000

但我得到了这个

你的圈子: 8.000000 0.000000 0.000000 28.260000

格式是

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

【问题讨论】:

  • 显示数组是如何声明的。
  • 看来你需要使用下面的循环 for(int x = 0; x
  • 什么输出?请在此处显示更多代码,以便我们查看完整图片。
  • @VladfromMoscow 已经编辑好了@tadman 我使用普通的二维数组输出for(int i = 0; i &lt;= circlerow; i++) { printf("\n"); for(int j = 0; j &lt;= circlecol; j++ ) { printf("\t%f", circles[i][j]); } }

标签: c arrays loops for-loop


【解决方案1】:

改变这个:

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

到这里:

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

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

同样,你会做for(int j = 0; j &lt; 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;
}

【讨论】:

  • 我使用circlerow作为数组本身所以圆的行数实际上是2,但我输入它为1,我已经为数组格式编辑了我的帖子。
  • @AldiandyaIrsyadNurFarizi 我看到了,看看我更新的答案,我相信它现在有效。 :)
【解决方案2】:

这个数组

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];
    }
}

也就是说数组应该有两行两列。

【讨论】:

  • 啊,它有效,但它的意思不是真的一样吗?我的意思是因为数组从 0 开始,以 2 结束,你只需使用
  • @AldiandyaIrsyadNurFarizi 不,array[x][y] 的大小为 xyarray[0][0]是第一行第一列的元素,array[x - 1][y - 1]是最后一列最后一行的元素。
  • @AldiandyaIrsyadNurFarizi 如果数组有 N 个元素,则索引的有效范围为 [0, N)。因此,您必须再添加一行和一列,并使用循环 c
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-21
  • 2014-06-22
  • 2019-10-16
  • 2022-01-24
  • 2023-03-23
  • 1970-01-01
相关资源
最近更新 更多