for (--index;index >= 0; --index) {
nextDigit = convertedNumber[index];
printf ("%c", baseDigits[nextDigit]);
}
这段代码看不懂,怎么就能做到逆序展示了?
尤其是
for里面的后面一个;--index?
nextDigit什么用?
希望能详细讲解下 谢谢各位大神
// Program to convert a positive interger another base
#include <stdio.h>
int main (void)
{
const char baseDigits[16] = {'0','1','2','3','4','5','6','7',
'8','9','A','B','C','D','E','F' };
int convertedNumber[64];
long int numberToConvert;
int nextDigit, base, index = 0;
// get the number and the base
printf ("Number to be converted?");
scanf ("%ld", &numberToConvert);
printf("Base?");
scanf ("%i",&base);
// convert to the indicated base
do {
convertedNumber[index] = numberToConvert % base;
++index;
numberToConvert = numberToConvert / base;
}
while (numberToConvert != 0);
//dispaly the result in the reverse order
printf(" Converted number = ");
for (--index;index >= 0; --index) {
nextDigit = convertedNumber[index];
printf ("%c", baseDigits[nextDigit]);
}
printf("\n");
return 0;
}
还有下面这段话 划线部分也是觉得有些难以理解
for循环的循环变量是index,并且每循环一次减一,而进制转换后的数字的位数是从低到高的,所以逆序后为真正的转换后的数字。
例如十进制10转换二进制,禁止转换后convertedNumber数组的内容是[0,1,0,1],index为3,所以倒着输出后是1010.
PS:
10 % 2 = 0(5), convertedNumber[0] = 0,
5 % 2 = 1(2), convertedNumber[1] = 1,
2 % 2 = 0(1), convertedNumber[2] = 0,
1 % 2 = 0(0), convertedNumber[3] = 1