【发布时间】:2018-09-30 19:59:24
【问题描述】:
该程序从用户那里获取两个数组并将它们相加并打印总和。该程序使用嵌套的 for 循环来获取值并打印值。编译器返回错误 array1 未在此范围内声明。如果我删除总和打印部分,该程序也会停止工作。任何缩短程序的建议表示赞赏。
#include<stdio.h>
int a,b;
int i,j;
main()
{
printf("Enter the size of the array \n Rows : ");
scanf("%d",&a);
printf("Columns : ");
scanf("%d",&b);
int array[a][b];
printf("Enter the values of the %dx%d array : \n",a,b);
for(i=0;i<a;i++)
{
for(j=0;j<b;j++)
{
scanf("%d",&array[i][j]);
}
}
printf("The values of the First Matrix are :\n");
for(i=0;i<a;i++)
{
for(j=0;j<b;j++)
{
printf("%d\t",array[i][j]);
}
printf("\n");
}
int input;
printf("If you want to do further operations on Matrices press 1\n");
scanf("%d",&input);
if(input==1)
{
printf("Enter the size of the array \n Rows : ");
scanf("%d",&a);
printf("Columns : ");
scanf("%d",&b);
int array1[a][b];
printf("Enter the values of the %dx%d array : \n",a,b);
for(i=0;i<a;i++)
{
for(j=0;j<b;j++)
{
scanf("%d",&array1[i][j]);
}
}
printf("The values of the Second Matrix are :\n");
for(i=0;i<a;i++)
{
for(j=0;j<b;j++)
{
printf("%d\t",array1[i][j]);
}
printf("\n");
}
}
input = 0;
printf("If you want to add the two matrices press 1 \n");
scanf("%d",input);
int array2[a][b];
if(input==1)
{
for(i=0;i<a;i++)
{
for(j=0;j<b;j++)
{
array2[i][j] = array[i][j]+array1[i][j];
}
}
}
printf("The Sum of the first and Second array is : \n ");
for(i=0;i<a;i++)
{
for(j=0;j<b;j++)
{
printf("%d\t",array2[i][j]);
}
printf("\n");
}
}
【问题讨论】:
-
main()int main(void) 和int main(int argc, void **argv)。实现也可以免费支持其他原型,但简单的main()不太可能是正确的。 -
除此之外,无需查看代码:它会帮助您先自己进行一些调试。有一篇很好的博文 How to debug small programs 可以指导您。如果您仍然卡住,它还将帮助您创建一个minimal reproducible example,这将反过来帮助其他人快速了解具体问题并提供帮助。
-
@FelixPalmen 程序无法编译,因此此时调试指令将无济于事。
-
编译器返回错误array1 not declared in this scope ? 因为
array1是在if(input==1)块内声明的,而您在该范围外访问。 -
很可能您的变量范围太窄,如果您遵循缩进代码的标准模式之一,这很明显。 (我使用 K & R 样式,但在
)和{之间没有空格)。
标签: c for-loop matrix multidimensional-array nested-loops