我在一本C语言书中找到了这个例子。此代码转换输入数字基并将其存储在数组中。
#include <stdio.h>
int main(void)
{
const char base_digits[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
int converted_number[64];
long int number_to_convert;
int next_digit, base, index = 0;
printf("type a number to be converted: \n");
scanf("%ld", &number_to_convert);
printf("Base\n");
scanf("%i", &base);
do
{
converted_number[index] = number_to_convert % base;
++index;
number_to_convert = number_to_convert / base;
}
while (number_to_convert != 0);
// now display the number
printf("converted number = :");
for (--index; index >= 0; --index )
{
next_digit = converted_number[index];
printf("%c", base_digits[next_digit]);
}
printf("\n");
return 0;
}我搞不懂最后一个for循环。它应该有助于逆转数组,但我不明白如何!
这一行是什么意思:for (--index; index >= 0; --index)
发布于 2017-10-21 21:37:07
回想一下,for头有三个部分:
通常,声明/初始化部分设置一个新的循环变量。但是,它不需要这样做。特别是,当多个循环共享相同的循环变量时,初始化部分调整现有值或完全丢失。
这正是你所处的情况。do/while循环将index提升到数组结束后的1。如果您需要从converted_number后面开始处理,则需要在进入循环之前减少index,然后在每次迭代时也减少它。
请注意,另一种可能是在while上使用带有预减量的index循环。
while (index > 0) {
next_digit = converted_number[--index];
printf("%c", base_digits[next_digit]);
}https://stackoverflow.com/questions/46868312
复制相似问题