gpt4 book ai didi

c - 如何仅使用for循环在C中向后打印输入的字符串

转载 作者:太空宇宙 更新时间:2023-11-04 00:22:42 25 4
gpt4 key购买 nike

我想向后打印一个字符串。但是我的代码似乎是从数组中的最后一个字母到数组中的第一个字母倒数字母表,而不是倒数数组本身并吐出数组中的每个字母。

我的代码,

   #include <stdio.h>
#include <string.h>

int main(void) {

char word[50];
char end;
char x;

printf("Enter a word and I'll give it to you backwards: ");

scanf("%s", word);

end = strlen(word) - 1;

for (x = word[end]; x >= word[0]; x--) {
printf("%c", x);
}

return 0;
}

有什么建议吗?谢谢。

最佳答案

数组元素值之间的循环。你想在数组索引之间循环。将循环更新为以下内容:

for (x = end; x >= 0; --x) {
printf("%c", word[x]);
}

请注意,这是从最后一个索引到零并输出该索引处的字符。也是 for 循环中使用预递减的微优化。

关于c - 如何仅使用for循环在C中向后打印输入的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4331347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com