[英]Why is my program ending after the first for loop?
我正在编写一个可以计算出幻方的程序,但是我无法使输入正常工作。 我很确定我正在用值填充数组,但是它在前两个for循环之后立即结束。 前两个应该打印数组,但是程序在输入数据后立即结束。 我会将循环放在错误的位置吗?
#include <stdio.h>
#define SIZE 15
int main(){
declareArray();
return 0;
}
int declareArray(){
int rowNumber = 0;
int dimension=0;
int arr[SIZE][SIZE] = {0};
int col = 0;
int row = 0;
printf("Please enter the dimension of the square: ");
scanf("%d", &dimension);
arr[dimension][dimension];
for(row; row<dimension; ++row)
for(col; col<dimension; ++col){
printf("Please enter the data for row %d: ", ++rowNumber$
scanf("%d", &arr[row][col]);
}
for(row; row<dimension; ++row){
for(col; col<dimension; ++col){
printf("%d", arr[row][col]);
}
}
return 0;
}
我的输入是:
3
123
456
789
我的预期输出是
123
456
789
我得到的是:
123
0
0
456
0
0
789
0
0
第一次循环后,您需要将row和col重置为0:
for(row = 0; row<dimension; ++row)
for(col = 0; col<dimension; ++col)
{
printf("Please enter the data for row %d: ", ++rowNumber$
scanf("%d", &arr[row][col]);
}
for(row = 0; row<dimension; ++row)
{
for(col = 0; col<dimension; ++col)
{
printf("%d", arr[row][col]);
}
}
保持循环初始化计数器变量的习惯,否则会很危险。
您需要在for
循环的第一部分中写入初始值。 所以代替
for(row; row<dimension; ++row)
和
for(col; col<dimension; ++col)
采用
for(row = 0; row < dimension; ++row)
和
for(col = 0; col < dimension; ++col)
同样非常重要,在第二个循环中使用变量之前,需要重新初始化row
和col
。 现在,当您到达第二个循环(打印一个)时, row
和col
将已经等于第一个循环(读取一个)的dimension
,因此您将永远不会进入第二个循环。
for(row = 0; row<dimension; ++row)
{
for(col = 0; col<dimension; ++col)
{
printf("%d", arr[row][col]);
}
}
最后,您的程序应为:
#include <stdio.h>
#define SIZE 15
int main(){
declareArray();
return 0;
}
int declareArray(){
int rowNumber = 0;
int dimension=0;
int arr[SIZE][SIZE] = {0};
int col = 0;
int row = 0;
printf("Please enter the dimension of the square: ");
scanf("%d", &dimension);
arr[dimension][dimension];
for(row=0; row < dimension; ++row)
for(col=0; col < dimension; ++col){
printf("Please enter the data for row %d: ", ++rowNumber);
scanf("%d", &arr[row][col]);
}
for(row=0; row < dimension; ++row){
for(col=0; col < dimension; ++col){
printf("%d", arr[row][col]);
}
}
return 0;
}
注意 :我认为您应该更改声明
printf("Please enter the data for row %d: ", ++rowNumber);
至 :
printf("Please enter the data for element %d: ", ++rowNumber);
当您读取每个框(而不是行)的元素时,将变量rowNumber
更改为elementNumber
。
您没有正确初始化循环变量,当完成第一对循环时,它们的( col
和row
)值已经等于dimension
,这会使第二对循环的循环条件无效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.