我是 C 的新手,我需要帮助来完成这个使用 for
的简单练习。我需要从用户那里得到一个 char
和一个 int
值。然后我必须打印 char
与之前输入的 int
一样多的次数。
这是我的:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char a;
printf("Enter a character:");
scanf(" %c", &a);
int n;
printf("Enter a number:");
scanf(" %c", &n);
printf("\n");
int x;
for(x=0; x < n; x++){
printf(" %c", a);
}
return 0;
}
我的问题是它在 for
中形成无限循环。
我需要你的帮助。
谢谢
最佳答案
这里,n
是一个int
,而不是一个char
。因此,您需要使用 %d
来阅读它。在此处使用 %c
将导致未定义的行为。根据 “C99 – ISO 9899-1999”:
§7.19.6.2 The
fscanf
function1[...] If this object does not have an appropriate type, or if the result of the conversion cannot be represented in the object, the behavior is undefined.
改变
scanf(" %c", &n);
到
scanf(" %d", &n);
查看 here了解更多信息。
<子>
1:scanf
函数等同于插入参数 stdin
的 fscanf
在 scanf
的参数之前。
关于c - 简单的for循环无限运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23273976/