我是C语言的新手,我想弄清楚为什么我的代码返回错误的值。
int main()
{
printf("Welcome to my number generator! \n");
printf("What is the first number in the range? \n");
int rng1 = scanf("%d", &rng1);
printf("What is the second number in the range? \n");
int rng2 = scanf("%d", &rng2);
printf("What would increment would you like to go up in? \n");
int inc = scanf("%d", &inc);
do
{
printf("%d\n"rng1);
rng1 += inc;
}
while(rng1 != rng2);
}
return 0;
}
从此代码中,我期望第一个范围和第二个范围之间的数字列表以某个数字递增,但是我得到的值为1。我在做什么错呢?PS我试图对其进行“调试”,发现使用以下命令时:
if(isalpha(rng1));
printf("I am a String...")
if(isdigit(rng1))
printf("I am a Digit")
它返回“我是弦乐...”。
谢谢!
您已经为变量分配了输入值rng1
,rng2
并inc
通过调用scanf
和还scanf
成功填充了参数列表的项数。因此,将的返回值分配scanf
给这些变量是不正确的。只需将返回值用作输入数量即可。您应该读取值1
,因为您只希望读取一个值scanf
。此外,您还可以检查输入值,以检测输入的值是否有效。
除此之外,我想对您的代码进行一些修改。特别是do{...}while();
由于!=
操作员,您的循环可能会无限期地运行。请在下面的代码中查看注释。
int main()
{
/* Declare the variables and do not assign the return value of scanf */
int rng1, rng2, inc;
printf("Welcome to my number generator! \n");
printf("What is the first number in the range? \n");
/* repeat this check condition for each scanf, exit( EXIT_FAILURE ) requires #include <stdlib.h>*/
if (1 != scanf("%d", &rng1)) {
exit( EXIT_FAILURE );
}
printf("What is the second number in the range? \n");
scanf("%d", &rng2);
printf("What would increment would you like to go up in? \n");
scanf("%d", &inc);
do
{
printf("%d\n",rng1);
rng1 += inc;
}
/* Use <= instead of != and think about the case for rng1 is 1 rng2 is 5 and inc is 3, can you detect the end of the loop by adding 3 to the starting point 1 ? */
while(rng1 <= rng2);
/* Remove the `}` here */
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句