gpt4 book ai didi

c - 在以下 C 程序中,如果条件不起作用

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

#include <stdio.h>
#include <conio.h>
#include <ctype.h>
#include <stdlib.h>
#include <time.h>

main()
{
int iRandom;
int iResponse;
srand(time(0));

iRandom = (rand() % 10) + 1;

printf("\nGuess a number between 1 and 10: ");
scanf("%c", &iResponse);

if (isdigit(iResponse)) {

iResponse = iResponse - '0';

if (iResponse >=1 && iResponse <=10 ) {


if (iResponse == iRandom) {
printf("\nYou guessed right.\n");
}
else {
printf("\nSorry, you guessed wrong.\n");
printf("The correct guess was %d\n", iRandom);
}
}
else {
printf("You did not enter a digit between 1 and 10.");
}

}
else {
printf("\nYou did not enter a digit.\n");
}

getch();
return 0;
}

如果 (iResponse >=1 && iResponse <=10 ) 不起作用,请检查此条件。在这种情况下,如果 iResponse <= 10 为 false,则不会执行 else 部分。任何解决方案请帮助我。

最佳答案

我认为你的意思是以下内容

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <errno.h>

int main( void )
{
char line[20];
unsigned int iRandom;
unsigned int iResponse;

const unsigned int Base = 10;

srand( ( unsigned int )time( NULL ) );

iRandom = rand() % Base + 1;

printf( "\nGuess a number between 1 and %u: ", Base );
scanf( "%20s", line );

errno = 0;
iResponse = ( unsigned int )strtoul( line, NULL, Base );

if ( !errno && iResponse >= 1 && iResponse <=10 )
{
if ( iResponse == iRandom )
{
puts( "\nYou guessed right." );
}
else
{
puts( "\nSorry, you guessed wrong." );
printf( "The correct guess was %u\n", iRandom );
}
}
else
{
puts( "\nYou did not enter a number" );
}

return 0;
}

程序输出可能如下所示

Guess a number between 1 and 10: A
You did not enter a number

Guess a number between 1 and 10: 4
Sorry, you guessed wrong.
The correct guess was 3

Guess a number between 1 and 10: 4
You guessed right.

至于你的代码,至少在这个声明中

scanf("%c", &iResponse);

您应该将“%c”替换为“%c”(%c之前有一个空格)。即使在这种情况下,结果也将由实现定义。此外,使用这种方法您将无法输入可接受的数字10。:)

关于c - 在以下 C 程序中,如果条件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31448552/

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