功能:把str1 数组中下标为偶数的元素中字符复制到str2 数组中。 -----------------------------------------------------*/ #include<stdio.h> #include<string.h> void main( ) { char str1[30],str2[20]; int i=0,j=0; printf("Please input str1: "); gets(str1); /**********FOUND**********/ while(str1[i]=0) { str2[j]=str1[i]; j++; /**********FOUND**********/ i=i+1; } str2[j]='\0'; printf("output str2:%s\n",str2); }
时间: 2023-06-29 15:07:24 浏览: 197
代码存在一些错误,应该是:
```
#include <stdio.h>
#include <string.h>
int main() {
char str1[30], str2[20];
int i = 0, j = 0;
printf("Please input str1: ");
gets(str1);
while(str1[i] != '\0') {
if(i % 2 == 0) {
str2[j] = str1[i];
j++;
}
i++;
}
str2[j] = '\0';
printf("output str2: %s\n", str2);
return 0;
}
```
修改点:
1. `main()` 函数缺失;
2. 初始化数组时应该为 `=` 而不是 `= 0`;
3. 判断字符串是否结束时应该是 `str1[i] != '\0'`;
4. 只复制下标为偶数的字符;
5. 缺少返回值。
相关问题
程序改错功能:把str1 数组中下标为偶数的元素中字符复制到str2 数组中。
以下是正确的程序:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "hello world";
char str2[100];
int len = strlen(str1);
for (int i = 0; i < len; i += 2) {
str2[i] = str1[i];
}
str2[len] = '\0';
printf("str1: %s\n", str1);
printf("str2: %s\n", str2);
return 0;
}
```
程序说明:
1. 定义 `str1` 和 `str2` 两个字符数组,并初始化 `str1`;
2. 使用 `strlen()` 函数获取 `str1` 的长度,存放在 `len` 变量中;
3. 使用 `for` 循环遍历 `str1` 数组,从下标为 0 开始,每次增加 2;
4. 在循环中,将 `str1` 中下标为偶数的元素中的字符复制到 `str2` 数组中;
5. 在循环结束后,需要在 `str2` 的最后一个位置添加上字符串结束符 `'\0'`,否则可能会输出乱码;
6. 最后,使用 `printf()` 函数分别输出 `str1` 和 `str2` 的值。
C输出字符数组中下标为偶数的字符
你好,我是 ChitGPT,很高兴回答你的问题。
要输出字符数组中下标为偶数的字符,可以使用循环语句和条件语句来实现。具体代码如下:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, world!";
int len = strlen(str);
for (int i = 0; i < len; i++) {
if (i % 2 == 0) {
printf("%c ", str[i]);
}
}
return 0;
}
```
以上代码中,首先定义了一个字符数组 `str`,并且使用 `strlen()` 函数获取了它的长度。然后使用 `for` 循环遍历整个字符数组,如果当前下标是偶数,则使用 `printf()` 函数输出该字符。
希望我的回答能对你有所帮助,如果你还有其他问题,可以随时问我哦!
相关推荐
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)