我在一本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 (--index; index >= 0; --index)
? 最佳答案
回想一下for
标题有三个部分:
在循环之前执行一次的声明/初始化部分,
在每次迭代之前执行的结束条件检查器,以及
将循环向前推进到下一个迭代的部分
通常,声明/初始化部分会设置一个新的循环变量。但是,并不要求这样做。特别是,当多个循环共享相同的循环变量时,初始化部分调整现有值或完全丢失。
这正是你的处境。do
/while
循环前进index
到超过数组末尾的一个。如果需要从converted_number
的后面开始处理,则需要在进入循环之前减小index
,然后在每次迭代时也减小它。
注意,另一种可能是在while
上使用带有预减量的index
循环:
while (index > 0) {
next_digit = converted_number[--index];
printf("%c", base_digits[next_digit]);
}
关于c - 该语句背后的逻辑是什么:for(--index; index> = 0; --index)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46868312/