|
发表于 2020-4-11 23:41:29
|
显示全部楼层
本帖最后由 奇宝 于 2020-4-12 00:38 编辑
//疑问:输出结果不对,代码哪里错了呢?
//题目:写一个函数,使输入的一个字符串按反序存放,在主函数中输入和输出字符串。
#include<stdio.h>
#include<iostream>
void inverse(char str[]);
char news[20];
int main()
{
char str[20];
printf("input string:");
scanf("%s", str);
inverse(str);
printf("%s", news);
}
void inverse(char str[])
{
int count = 0, i;
for (i = 0; i < 20; i++)//计算str数组的长度
{
if (str[i] == '\0')
break;
count = count + 1;//count放到后面增加就不会比i多一了,为了简便,可以写成--> ++count;
}
/*count = count - 1;*///count比i多加了一次,所以减一才对把?(如上,即可不必减一)
for (i = 0; i < count; i++)//把倒序后的数据存在new数组里
{
news[ i ] = str[count - 1 - i];//如果在这里更改count,会造成for循环的count减少
//,所以应该这样,减一是为了避免引进 "\0"
}
news[count] = '\0';
} |
|