gpt4 book ai didi

C、帮助 while 循环在不为 true 时继续

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

任务:编写一个 char do/while 循环,如果字母不是大写则程序将结束:

解决方案:

Char input;

do{
scanf("%c", &input);

} while (input <'a' || 'z'< input);

所以我的程序说:“执行此操作,同时输入是 a 或 z”。为什么它控制从 a 到 z 的所有字母,如果它是一个小字符而不是大写字母,我的程序怎么会结束?

我是 C 新手,我在任何地方都找不到解释,提前致谢。

最佳答案

问题是这样的陈述:

while (input <'a' || 'z'< input);

因为这是寻找任何非小写字母的内容,并且没有考虑整个 ascii(单字符)可能性表。

标准是大写,而这些字母是小写。

你可以使用:

while ('A' <= input && input <= 'Z')

但是,最好使用头文件中的功能:ctype.h,因为并非所有系统都使用 ASCII 字符集。 (例如,IBM 大型机使用 EBCDIC 而不是 ASCII,其中字母表不连续)

请记住,“enter”键不是大写(并且在代码中不允许)

以下建议代码:

  1. 干净地编译
  2. 执行所需的功能
  3. 正确检查错误
  4. 使用头文件ctype.h中定义的功能

现在是建议的代码

#include <stdio.h>   // scanf(), perror()
#include <stdlib.h> // exit(), EXIT_FAILURE
#include <ctype.h> // isupper()


int main( void )
{
// 'char' is all lower case:
// so this statement: Char input;
// does not compile, suggest:
char input;

do
{
int scanfStatus = scanf("%c", &input);
// always check the returned value (not the parameter value)
if( 1 != scanfStatus )
{
perror( "scanf failed" );
exit( EXIT_FAILURE );
}
} while ( isupper( input ) );
} // end function: main

关于C、帮助 while 循环在不为 true 时继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44473748/

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