请补充函数fun,该函数的功能是:把一个整数转换成字符串,并倒序保存在字符数组str中。 例如,当n=13572468时,str="86427531"。 注意:部分源程序给出如下。 请勿改动main函数和其他函数中的任何内容,仅在函数fun的横线上填入所编写的若干表达式或语句。 试题程序:*/ #include <stdlib.h> #include <stdio.h> #define N 80 char str[N]; void fun(long int n) { int i=0; /**********FILL**********/ while( [1] ) { /**********FILL**********/ str[i]= [2] ; n/=10; i++; } /**********FILL**********/ [3] ; } int main() { long int n=13572468; printf("*** the origial data ***\n"); printf("n=%ld",n); fun(n); printf("\n%s",str); return 0; }
时间: 2023-08-20 21:04:46 浏览: 49
#include <stdlib.h>
#include <stdio.h>
#define N 80
char str[N];
void fun(long int n) {
int i=0;
while(n!=0) { // [1] 当n不等于0时循环
str[i]=n%10+'0'; // [2] 将n的个位转换为字符并存入str中
n/=10;
i++;
}
str[i]='\0'; // [3] 在str末尾添加结束符'\0'
}
int main() {
long int n=13572468;
printf("*** the origial data ***\n");
printf("n=%ld",n);
fun(n);
printf("\n%s",str);
return 0;
}
相关问题
请编写函数 fun,函数的功能是:在字符串中的所有数字字符前加一个$字符。(C语言)
以下是函数fun的代码实现:
```c
void fun(char *str) {
int i = 0;
while (str[i] != '\0') { // 遍历整个字符串
if (str[i] >= '0' && str[i] <= '9') { // 判断是否为数字字符
int j = i;
while (str[j] != '\0') { // 将数字字符后面的字符全部后移一位
str[j + 1] = str[j];
j++;
}
str[i] = '$'; // 在数字字符前插入$字符
i += 2; // 跳过$字符和移动的字符
} else {
i++;
}
}
}
```
使用方法如下:
```c
#include <stdio.h>
void fun(char *str);
int main() {
char str[100];
printf("请输入字符串:");
gets(str);
fun(str);
printf("处理后的字符串为:%s", str);
return 0;
}
```
功能:编写函数fun求一个字符 串的长度,在main函数中 输入字符串,并输出其长度。
好的,下面是实现该功能的C++代码:
```cpp
#include <iostream>
using namespace std;
int fun(char str[]) {
int len = 0;
while (str[len] != '\0') {
len++;
}
return len;
}
int main() {
char str[100];
cout << "请输入一个字符串:";
cin >> str;
int len = fun(str);
cout << "该字符串的长度为:" << len << endl;
return 0;
}
```
在上述代码中,我们编写了一个名为`fun`的函数,该函数接受一个字符数组作为参数,并返回该字符数组的长度。在`main`函数中,我们首先声明一个字符数组`str`,并通过`cin`从控制台输入一个字符串。然后,我们调用`fun`函数计算该字符串的长度,并将其输出到控制台上。