我是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.我做错了什么? 附:我试图调试'它发现我用的时候:
if(isalpha(rng1));
printf("I am a String...")
if(isdigit(rng1))
printf("I am a Digit")
它回来了,"我是一个字符串..."。
谢谢!
答案 0 :(得分:2)
您已经通过调用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;
}
答案 1 :(得分:1)
当您传递变量的地址(使用&
运算符)时,您允许scanf
将扫描值写入变量。 scanf
的返回值不您要查找的值(它是其他内容)。
因此,当您将scanf
的返回值分配给变量时,您将覆盖已有的正确值。这应该有效:
int rng1;
scanf("%d", &rng1);
答案 2 :(得分:1)
应始终检查scanf()
的返回值以确保成功运行。
格式字符串应该(几乎)总是包含一个前导空格''
所以跳过/消耗了左上方的空格(如换行符)
因此,代码应该更像:
int rng1;
if( 1 != scanf(" %d", &rng1) )
{ // then, scanf failed
perror( "scanf for rng1 failed" );
exit( EXIT_FAILURE );
}
// implied else, scanf for rng1 successful
答案 3 :(得分:0)
上面两条评论说明scnaf()有返回值只是为了检查成功的操作。但是,您需要阅读的值是第二个参数。 我还可以在代码中看到括号不匹配。
int main(int argc, char **argv)
{
printf("Welcome to my number generator! \n");
printf("What is the first number in the range? \n");
int rng1;
int t = scanf("%d", &rng1); // First scanned value stored in rng1 variable
printf("What is the second number in the range? \n");
int rng2;
int t1 = scanf("%d", &rng2); // Second scanned value stored in rng2 variable
printf("What would increment would you like to go up in? \n");
int inc;
int t2 = scanf("%d", &inc); // Third scanned value stored in inc variable
do
{
printf("%d\n",rng1);
rng1 += inc;
}
while(rng1 <= rng2); // repeat until rng1 reaches value of rng2
return 0;
}
在这里使用临时变量t,t1和t2,您可以验证是否成功扫描了这些值。