用c语言实现程序要求能够提取输入的字符串中的数字,将数字累加,得到数字之和,如输入的字符串为"abc76wet23er1.",应该提取数字76,23,1,求和后,即76+23+1=100,要求输入的字符串最后一个字符不能为数字字符。
时间: 2024-05-05 07:16:37 浏览: 16
```c
#include <stdio.h>
int main() {
char str[100];
int i, sum = 0;
printf("请输入一个字符串:");
scanf("%s", str);
if (str[strlen(str)-1] >= '0' && str[strlen(str)-1] <= '9') {
printf("输入的字符串最后一个字符不能为数字字符!\n");
return 0;
}
for (i = 0; str[i] != '\0'; i++) {
if (str[i] >= '0' && str[i] <= '9') {
int num = str[i] - '0';
while (str[i+1] >= '0' && str[i+1] <= '9') {
num = num * 10 + (str[i+1] - '0');
i++;
}
sum += num;
}
}
printf("数字之和为:%d\n", sum);
return 0;
}
```
相关问题
用c语言写输入字符串,将字符串中的数字字符转化成数字,将数字累加,输出得到数字之和
好的,以下是 C 语言的实现代码:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
int i, sum = 0;
printf("请输入字符串:");
scanf("%s", str);
for (i = 0; i < strlen(str); i++) {
// 判断当前字符是否为数字字符
if (str[i] >= '0' && str[i] <= '9') {
// 将数字字符转化成数字,累加到总和中
sum += str[i] - '0';
}
}
printf("得到数字之和为:%d\n", sum);
return 0;
}
```
例如,如果输入字符串为 `"Hello123World456"`,则输出结果为:
```
得到数字之和为:21
```
C语言实现输入一个字符串(字符串长度不超过100),将字符串中的数字字符转换成数字,将数字累加
好的,以下是 C 语言的示例代码:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str_input[101];
int total = 0;
int i = 0;
printf("请输入一个字符串:");
scanf("%s", str_input);
while (str_input[i] != '\0') {
if (isdigit(str_input[i])) {
total += str_input[i] - '0'; // 将字符转换为数字并累加
}
i++;
}
printf("字符串中所有数字的和为:%d\n", total);
return 0;
}
```
你可以复制这段代码并在 C 语言编译器中运行它,或者直接在我的对话框里输入你的字符串,我会帮你计算出数字的和。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)