gpt4 book ai didi

c - scanf single char 不适用于我的循环

转载 作者:行者123 更新时间:2023-11-30 18:30:10 25 4
gpt4 key购买 nike

所以我一直在编写二维寻宝的代码,其中我使用 scanf 中的单个字符,无论它是 n、s、w、e,它都会执行特定的输出。不幸的是,我的代码没有监听我的输入,例如,当我输入 n 时,什么也没有发生。我想知道你们能否指出我正确的道路

do
{
printf("Please press n, s, w, or e to find the treasure\n");
scanf(" %c", &n);
if (scanf(" %c", &n) == 'n')
{
current - 11;
new = current - 11;
if (abs(potofgold - current) < abs(potofgold - new))
printf("getting warmer\n");
else if (abs(potofgold - current) > abs(potofgold - new))
printf("Getting colder\n");
else
printf("Hooray\n");
current = new;
}
else if (scanf("%c", &s) == 's')
{
current + 11;
new = current + 11;
if (abs(potofgold - current) < abs(potofgold - new))
printf("Getting warmer\n");
else if (abs(potofgold - current) > abs(potofgold - new))
printf("getting colder\n");
else
printf("Hooray\n");
current = new;
}
else if (scanf("%c", e) == 'e')
{
current + 1;
new = current + 1;
if (abs(potofgold - current) < abs(potofgold - new))
printf("getting warmer\n");
else if (abs(potofgold - current) > abs(potofgold - new))
printf("getting colder\n");
else
printf("Hooray\n");
current = new;
}
else (scanf("%c", &w) == 'w');
{
current - 1;
new = current - 1;
if (abs(potofgold - current) < abs(potofgold - new))
printf("getting warmer\n");
else if (abs(potofgold - current) > abs(potofgold - new))
printf("getting colder\n");
else
printf("Hooray\n");

current = new;
}
}
while (current != potofgold);

return 0;

最佳答案

这些条件在任何情况下都不会成立 -

if (scanf(" %c", &n) == 'n')       // compare variable with character n=='n' 
....
else if (scanf("%c", &s) == 's') // s=='s'
....
else if (scanf("%c", e) == 'e') // e=='e'
^ & missing here

scanf 在每种情况下都会在成功时返回 1 。不要将其与字符进行比较。

相反,您可以编写这样的条件 -

 if (scanf(" %c", &n) == 1 && n=='n')     // if scanf will be successful then only n=='n' will be evaluated. Thus , on failure of scanf scond condition will not be evaluated
....
else if (scanf("%c", &s) ==1 && s=='s')
....
else if (scanf("%c", &e) == 1 && e=='e')

这应该是else if-

 else (scanf("%c", &w) == 'w');   // else ends here (It should be else if)
{ // this is after else part
current - 1; // remove this , compiler will issue an error\warning
new = current - 1;
if (abs(potofgold - current) < abs(potofgold - new))
printf("getting warmer\n");
else if (abs(potofgold - current) > abs(potofgold - new))
printf("getting colder\n");
else
printf("Hooray\n");

current = new;
}

还有这些

 current - 11;  // do you mean current-=11;
current + 11; // as current+=11;
current +1 ; // as current +=1;
current -1 ; // as current -=1;

关于c - scanf single char 不适用于我的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32793114/

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