[英]Array input is getting one more entry than should be
My code isn't wrong but here's the problem .我的代码没有错,但这就是问题所在。 As you can see, the last element shouldn't appear, although it doesn't get counted it's annoying.
正如你所看到的,最后一个元素不应该出现,虽然它没有被计算在内,但很烦人。
Here's my code:这是我的代码:
int mat[3][4] = {0};
int i, j;
for(i = 0; i < 3; i++){
for(j = 0; j < 4; j++){
printf("insert the element [%d][%d]", i, j);
scanf("%d ", &mat[i][j]);
}
}
printf("\nmatrix: \n");
for(i = 0; i < 3; i++){
for (j = 0; j < 4; j++){
printf("%3d ", mat[i][j]);
}
printf("\n");
}
Check here: You faced the problem because of white space in scanf()在这里检查:由于 scanf() 中的空白,您遇到了问题
What actually happens when you ask scanf to read numeric data, it first skips any white space it finds, and then it reads characters until that character cannot form part of a number.当您要求 scanf 读取数字数据时实际发生了什么,它首先跳过它找到的任何空格,然后读取字符,直到该字符不能构成数字的一部分。
#include <stdio.h>
int main()
{
int mat[3][4] = {0};
int i, j;
for(i = 0; i < 3; i++){
for(j = 0; j < 4; j++){
printf("insert the element [%d][%d] ", i, j);
scanf("%d", &mat[i][j]);
}
}
printf("\nmatrix: \n");
for(i = 0; i < 3; i++){
for (j = 0; j < 4; j++){
printf("%3d", mat[i][j]);
}
printf("\n");
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.