如何以C程序的相反顺序打印字符数组 [英] How to print character array in reverse order of C program
本文介绍了如何以C程序的相反顺序打印字符数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include <stdlib.h>
#include <stdio.h>
#define SIZE 25
int main (void)
{
int d, b, c;
printf(" Enter an integer and press 'enter':\n");
scanf("%d" , &d);
printf(" Enter the desired base and press 'enter':\n");
scanf("%d" , &b);
if (b < 2) {
printf(" Your base is to low! \n")
} else {
while (d != 0) {
int radix;
radix = d % b;
d = d / b;
char basechars[] = "0123456789ABCDEF";
printf("%c" , basechards[radix]);
}
}
return 0;
}
此程序提示用户输入一个十进制数和一个基数,以将该十进制数转换为所选的基数.但是,转换是按相反的顺序打印的,我需要它定期打印.示例:输入:112,然后输入16,结果是07,而不是70.
This Program prompts the user for a decimal and a base to convert that decimal to the base that has been chosen. The conversion is however printed in reverse order and I need it to print regular. Example: Entered: 112, then entered 16, result is 07 rather than 70.
推荐答案
您可以将每个数字存储在数组中:
You can store each digit in an array:
} else {
char arr[32];
int counter = 0;
while (d != 0) {
int radix;
radix = d % b;
d = d / b;
char basechars[] = "0123456789ABCDEF";
arr[counter++] = basechars[radix];
}
if (counter == 0)
arr[counter++] = '0';
arr[counter++] = '\0';
print_rev(arr);
printf("\n");
}
,然后使用递归函数打印字符串(它将反转输出):
and then print the string using a recursive function (it will reverse the output):
void print_rev(const char *s)
{
if (*s) {
print_rev(s + 1);
printf("%c", *s);
}
}
或直接:
} else {
char arr[32];
int counter = 0;
while (d != 0) {
int radix;
radix = d % b;
d = d / b;
char basechars[] = "0123456789ABCDEF";
arr[counter++] = basechars[radix];
}
if (counter == 0) {
printf("0");
else {
while (counter--)
printf("%c", arr[counter]);
}
printf("\n");
}
这篇关于如何以C程序的相反顺序打印字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文