gpt4 book ai didi

C程序检查输入的字符是否为数字?

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

我正在尝试通过模式检查来检查输入的字符是否为数字。

我编写了以下程序。

该程序没有为我提供以下测试用例的完美输出谁能告诉我我的逻辑哪里出了问题。

/*

Output test case

234234 = It's a digit.
a3434a = It's not a digit.
33aa3a = It' not a digit.

*/

#define yes 1
#define no 0

#include <stdio.h>

int main(void)
{
char c[30];
int arr_size, result, i=0, state;
printf("Enter your digit:= ");
scanf("%s",&c);

arr_size=(sizeof(c)/sizeof(c[0]));

for(i; i < arr_size; i++)
{
if(check_digit(c[i]))
state = yes;
else
state = no;
}

if(!state)
printf("It's not a digit\n");
else
printf("It's a digit\n");

system("\npause");
return 0;
}

int check_digit(char c)
{
return (c>='0' && c<='9');
}

最佳答案

  1. 您正在处理一个字符串。只需迭代直到找到“\0”。无需对 sizeof 感到奇怪。
  2. 读取man isdigit
  3. 如果您确实想向 scanf 传递指针,则需要为 &c[0]。然而,c 本身就是一个指针,所以你可以直接说 scanf("%s", c);
  4. 还有那个状态变量。尝试在纸上手工运行一些值,看看会发生什么。

关于C程序检查输入的字符是否为数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9064630/

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