初学C语言----反向输出一个四位数
题目:将一个四位数,反向输出。
(针对每组输入,反向输出对应四位数。)
示例
输入: 1234
输出: 4321
方法一:可以利用求余运算然后每次对10求商即可
#include
int main() {
int n = 0;
scanf(“%d”, &n);
//利用求余获取a的最后一位,以此类推
printf(“%d”, n% 10);
n /= 10;
printf(“%d”, n% 10);
n /= 10;
printf(“%d”, n% 10);
n /= 10;
printf(“%d\n”, n);
return 0;
}
方法二:在方法一的基础之上加上while循环
#include
int main()
{
int n = 0;
scanf(“%d”, &n);
while(n)
{
printf(“%d”, n%10);
n = n/10;
}
return 0;
}
方法三: 将数字以字符串读入,只要输出字符串后四位即可
#include
int main() {
char str[10];
scanf(“%s”, str);
printf(“%c%c%c%c\n”, str[3], str[2], str[1], str[0]);
return 0;
}
还没有评论,来说两句吧...