C语言设计一个子函数,统计任意一串字符中数字字符的个数,并在主函数中输入数据、调用此函数,并在主函数中输出结果
时间: 2024-05-06 16:17:10 浏览: 104
以下是一个示例代码:
```c
#include <stdio.h>
int countDigits(char *str) {
int count = 0;
while (*str != '\0') {
if (*str >= '0' && *str <= '9') {
count++;
}
str++;
}
return count;
}
int main() {
char str[100];
printf("请输入一串字符:");
scanf("%s", str);
int count = countDigits(str);
printf("这串字符中数字字符的个数为:%d\n", count);
return 0;
}
```
函数 `countDigits` 接受一个指向字符数组的指针,遍历字符串中的每个字符,如果该字符是数字字符,则计数器加一。主函数中先输入一串字符,然后调用 `countDigits` 函数并输出结果。
相关问题
c语言 设计一个子函数,统计任意一串字符中数字字符的个数,并在主函数中调用此函数
实现如下:
```c
#include <stdio.h>
int count_digits(char *str) {
int count = 0;
while (*str != '\0') {
if (*str >= '0' && *str <= '9') {
count++;
}
str++;
}
return count;
}
int main() {
char str[100];
printf("请输入任意一串字符:");
fgets(str, 100, stdin);
int count = count_digits(str);
printf("数字字符的个数为:%d\n", count);
return 0;
}
```
这段代码中,`count_digits` 函数用来统计字符串中数字字符的个数。在主函数中,我们先输入一串字符,然后调用 `count_digits` 函数进行统计,并输出结果。
c语言设计一个子函数,统计任意一串字符中数字字符的个数,并在主函数中调用此函数。
下面是一个简单的示例代码:
```c
#include <stdio.h>
int count_digits(char str[]) {
int count = 0;
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] >= '0' && str[i] <= '9') {
count++;
}
}
return count;
}
int main() {
char str[100];
printf("请输入一串字符:");
scanf("%s", str);
int count = count_digits(str);
printf("数字字符的个数为:%d\n", count);
return 0;
}
```
在上面的代码中,我们首先定义了一个名为 `count_digits` 的函数,该函数接收一个字符串作为参数,并返回其中数字字符的个数。在函数内部,我们使用了一个 `for` 循环来遍历字符串中的每个字符,如果当前字符是数字字符,则将计数器 `count` 加一。最后,函数返回计数器的值。
在主函数中,我们首先定义了一个字符数组 `str`,并使用 `scanf` 函数从标准输入中读取用户输入的字符串。接着,我们调用了 `count_digits` 函数来统计字符串中数字字符的个数,并将结果保存在变量 `count` 中。最后,我们输出了计数器的值。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)