编写函数fun(),将一个数字字符串转换成与之相同的整数。例如:如果输入的字符串为“12345”,则函数返回整数12345。要求函数的形参采用指针变量。
时间: 2024-03-01 21:51:29 浏览: 76
下面是一个将数字字符串转换成整数的C语言程序:
```c
#include <stdio.h>
#include <string.h>
int fun(char* str) {
int len = strlen(str);
int num = 0;
for (int i = 0; i < len; i++) {
num = num * 10 + (str[i] - '0');
}
return num;
}
int main() {
char str[100];
printf("请输入一个数字字符串:");
scanf("%s", str);
int num = fun(str);
// 输出
printf("转换后的整数为:%d", num);
return 0;
}
```
这里的`fun`函数将一个数字字符串转换成整数。采用循环遍历字符串中的每个字符,将它们转换成数字,并累加到`num`变量中。在`main`函数中,输入一个数字字符串后,调用`fun`函数,将字符串转换成整数并输出。
相关问题
:编写函数fun(),将一个数字字符串转换成与之相同的整数。例如:如果输入的字符串为“12345”,则函数返回整数12345。要求函数的形参采用指针变量。c语言
好的,以下是函数fun()的代码实现:
```c
#include <stdio.h>
int fun(char *str) {
int num = 0;
while (*str != '\0') {
num = num * 10 + (*str - '0');
str++;
}
return num;
}
int main() {
char str[20];
printf("请输入数字字符串:");
scanf("%s", str);
int num = fun(str);
printf("转换后的整数为:%d", num);
return 0;
}
```
函数fun()的作用是将输入的数字字符串转换成整数。它的形参采用指针变量,即指向字符数组的指针。函数内部使用了while循环遍历字符串中的每一个字符,并将其转换成对应的数字累加到num变量中,最终返回num作为转换后的整数。
c语言编写函数fun(),将一个数字字符串转换成与之相同的整数。例如:如果输入的字符串为“12345”,则函数返回整数12345。要求函数的形参采用指针变量。
可以使用C语言中的atoi()函数来实现将数字字符串转换成整数的功能。不过,这里我们可以自己编写一个函数来实现这个功能,代码如下:
```c
int strToInt(char* str) {
int result = 0; // 存储转换后的整数
char* p = str; // 定义指针变量p指向字符串的第一个字符
while (*p != '\0') {
result = result * 10 + (*p - '0'); // 将字符转换成数字并累加到result中
p++; // 指针p指向下一个字符
}
return result;
}
```
这个函数接收一个指向数字字符串的指针变量,然后遍历字符串中的每一个字符,将其转换成数字并累加到result中,最后返回转换后的整数。
阅读全文
相关推荐
![text/x-c](https://img-home.csdnimg.cn/images/20250102104920.png)
![c](https://img-home.csdnimg.cn/images/20250102104920.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)
![c](https://img-home.csdnimg.cn/images/20250102104920.png)
![c](https://img-home.csdnimg.cn/images/20250102104920.png)