C 语言 isdigit() 函数2024 年 8 月 28 日 | 阅读 6 分钟 本主题将讨论 C 语言中的 isdigit() 函数。isdigit() 函数是 C 库中预定义函数,用于检查字符是否为 0 到 9 的数字字符。如果给定字符是数字,则返回 true 布尔值或非零值;否则,返回零或 false 值。isdigit 函数在 ctype.h 头文件中声明,因此我们必须将其添加到 C 程序中。 例如,假设我们将字符 'h' 输入 isdigit() 函数;该函数检查输入字符是否为数字。此处字符不是数字。因此 isdigit() 函数返回零 (0) 或 false 值。同样,我们再次将数字字符 '5' 输入 isdigit() 函数。这次,函数返回 true 或非零值,因为 '5' 是 0 到 9 之间的数字字符。 isdigit() 函数的语法以下是 C 语言中 isdigit() 函数的语法。 参数Ch - 它定义要传递给 isdigit() 函数的数字字符。 返回值isdigit() 函数检查 'ch' 参数,如果传递的字符是数字,则返回非零值。否则,它显示零或 false 布尔值。 示例 1:检查给定字符是否为数字的程序让我们创建一个程序,使用 C 编程中的 isdigit() 函数检查给定字符是否为数字。 输出 The given character 'P' is not a digit. The given character '3' is a digit. The given character '!' is not a digit. The given character '$4' is not a digit. The given character '0' is not a digit. 在上面的程序中,我们定义了不同的字符,如 'P'、'3'、'!'、'$4'、0,以使用 isdigit() 函数检查这些字符是否有效。然后,我们使用 isdigit() 函数检查并返回字符 'P'、'1'、$4 不是数字。 示例 2:检查用户输入的字符是否为数字的程序让我们编写一个程序,使用 C 语言中的 isdigit() 函数查找输入字符是否有效。 输出 Enter a number to check for valid digits: 5 It is a digit. 在上面的程序中,我们从用户输入字符 '5',然后使用 isdigit 函数检查传递的参数是否为数字。此处,传递的字符是数字,因此 isdigit() 函数返回语句“它是数字”。 第二次执行 Enter a number to check for valid digits: A It is not a digit. 同样,当我们向 isdigit() 函数输入字符 'A' 时,该函数检查有效字符,我们可以看到字符 'A' 不是数字。因此,该函数返回语句“它不是数字”。 示例 3:为 C 语言中传递的字符打印零和非零数字的程序让我们编写一个程序,检查所有给定字符,并根据传递给 C 语言中 isdigit() 函数的字符返回零和非零值。 输出 The isdigit() function returns result based on character (0) passed: 1 The isdigit() function returns result based on character (o) passed: 0 The isdigit() function returns result based on character (08) passed: 1 The isdigit() function returns result based on character (+) passed: 0 The isdigit() function returns result based on character (%) passed: 0 在上面的程序中,我们使用 isdigit() 函数测试有效的给定数字字符。isdigit() 函数对数字字符返回 1,对程序中定义的字母或特殊符号(非数字)返回 0。 示例 4:使用 isdigit() 函数检查所有数组元素的程序让我们编写一个程序,使用 C 语言中的 isdigit() 函数查找数组元素的所有有效数字。 输出 'E' is not a valid digit character. '8' is a digit character. '@' is not a valid digit character. '-' is not a valid digit character. '3' is a digit character. '/' is not a valid digit character. '7' is a digit character. '$' is not a valid digit character. 在上面的程序中,我们声明并初始化了包含某些元素的 arr[] 变量。然后,我们创建另一个数组 arr2[],其中包含零 (0),用于将结果分配给那些不是有效数字的元素。isdigit() 函数检查所有 arr[] 数组元素,并对有效数字元素返回非零值。否则,它对非数字元素返回零 (0)。 |
我们请求您订阅我们的新闻通讯以获取最新更新。