[英]Why %d is showing 0 in my c program output?
该程序是在所有输入的整数中找到最大的数。 它要求用户输入一个数字 10 次或按 0 退出,以较早者为准。 但是,output 不如预期。 如果您能帮助新手,我将不胜感激。
#include <stdio.h>
int main()
{
int num[10];
int max, a;
for (a = 0; a < 10; a++)
{
printf("Enter the integer: ");
scanf("%d", &num[a]);
if (num[a] == 0)
break;
}
for(a = 0; a < 10; a++)
{
num[0] = max;
if(max < num[a])
{
num[a] = max;
}
}
printf("This is the largest integer: %d", max); //The output is coming wrong here.
return 0;
}
#include <limits.h>
int max = INT_MIN;
此外,您还需要按如下方式更改第二个 for 循环,以便在迭代时更新 max 变量,而不是 num[] 变量。 如果您之前已经假设 max 是第一个元素,则循环变量从 1 开始,否则循环变量将从 0 开始。
for(a = 1; a < 10; a++) // a=0 if max was initialized to INT_MIN above
{
if(num[a]>max)
{
max = num[a];
}
}
您永远不会分配max
变量。
您要做的是检查输入的值是否大于您之前输入的每个值,因此您需要使用以下条件:
if (num[a] > max)
max = num[a];
您还需要将max
初始化为某个值(比方说,如果您希望只有正整数,它可能是0
,但请查看Jigsaw答案以获得更好的解决方案): int max = 0;
.
并最终添加一个if-condition
来检查max
是否为0
,这样您就知道是否没有输入任何值:
if(max == 0)
printf("No values have been entered.");
else printf("This is the largest integer: %d", max);
请注意,您可以在同一个 for 循环中分配num
和 update max
的元素,因此第二个 for 变得完全无用,您可以将其删除:
#include <stdio.h>
int main()
{
int num[10];
int max = 0, a;
for (a = 0; a < 10; a++)
{
printf("Enter the integer: ");
scanf("%d", &num[a]);
if (num[a] == 0)
break;
if (num[a] > max)
max = num[a];
}
if(max == 0)
printf("No values have been entered.");
else printf("This is the largest integer: %d", max);
return 0;
}
我建议你打开你的编译器警告,尤其是-Wall
和-Wextra
,这样你会注意到这样的问题:
<source>: In function 'main':
<source>:17:16: warning: 'max' may be used uninitialized [-Wmaybe-uninitialized]
17 | num[0] = max;
| ~~~~~~~^~~~~
<source>:6:9: note: 'max' was declared here
6 | int max, a;
| ^~~
您既不初始化也不向变量max
写入任何值。 使用未初始化的变量是未定义的行为。
您似乎知道如何将 0 a
. 但是对于max
,你似乎把它颠倒了。 请记住,with =
右边的值进入到左边的变量中。
要解决此问题,请转动任何something = max;
在您的代码中出现max = something;
.
对于初学者来说,这个 for 循环
for (a = 0; a < 10; a++)
{
printf("Enter the integer: ");
scanf("%d", &num[a]);
if (num[a] == 0)
break;
}
由于条件,可以在数组num
中输入少于10
元素
if (num[a] == 0)
break;
所以下一个循环必须准确地遍历数组a
元素而不是10
。 因此,在下一个循环中,您必须为索引使用另一个变量,例如
for( int i = 0; i < a; i++)
变量max
未初始化
int max, a;
因此,此 for 循环调用未定义的行为,其中变量max
被分配给数组元素或与数组元素进行比较。
for(a = 0; a < 10; a++)
{
num[0] = max;
if(max < num[a])
{
num[a] = max;
}
}
此外,变量max
在 for 循环中没有改变。 所以整个循环没有意义。
注意用户可以一次输入0
。 因此该数组将不包含任何有效值。 在这种情况下,数组没有最大值。
例如,您的程序可以通过以下方式查看
#include <stdio.h>
int main( void )
{
enum { N = 10 };
int num[N];
int i = 0;
do
{
printf( "Enter the integer (0 - stop): " );
scanf( "%d", &num[i] );
} while ( num[i] != 0 && ++i < N );
int max_i = 0;
for ( int j = 1; j < i; j++ )
{
if ( num[max_i] < num[j] )
{
max_i = j;
}
}
if ( i == 0 )
{
puts( "You have not entered numbers unequal to zero." );
}
else
{
printf("This is the largest integer: %d", num[max_i] );
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.