gpt4 book ai didi

c - 为什么我的代码返回不正确的值?

转载 作者:太空宇宙 更新时间:2023-11-04 06:25:26 25 4
gpt4 key购买 nike

我是 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")

它返回,“我是一个字符串...”。

谢谢!

最佳答案

您已经通过调用 scanf 将输入值分配给变量 rng1rng2inc 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;
}

关于c - 为什么我的代码返回不正确的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27671884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com