为什么我的程序会跳过数字 8 和 9?
Why my program is skipping the digit 8 and 9?
我需要一些帮助。
我设计的程序给我第一个数字,然后跳过下一个数字,依此类推。但是每次遇到数字 8 时,结果都是 10 而不是 8,所以对于数字 9,结果将是 11。除了 8 和 9 之外的任何数字都不会发生这种情况。
经过多次尝试,我注意到当 sum1 达到 17 时重复同样的事情。如果您添加 1 或其他数字,它将跳过 18 和 19,并取值 20。
在我看来,好像程序是 1 2 3 4 5 6 7 10 11 12 13 14 15 16 17 20 21 22.
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int count = 8 ;
long number = 12345678 ;
long the_remainder ;
long sum1 = 0 ;
for (int i = 0 ; i < (count / 2) ; i++)
{
the_remainder = number % 10 ;
printf(" the_remainder is %lo\n", the_remainder);
number = number / 100 ;
sum1 = sum1 + the_remainder ;
printf("the sum is : %lo\n", sum1);
}
}
The result
%o
格式说明符以八进制格式输出,这就是值 8 显示为 10
的原因。
您想改用 %ld
,它以十进制打印。
您正在使用格式说明符 %o
,它将打印出 octal(即 base-8)整数。 base-8中显然没有数字8
或9
。
使用 %d
或 %ld
作为基数 10。
您应该尝试 %d
而不是 %o
。因为 %o
将打印八进制整数,而您预期的答案是以 10 为基数(十进制)。
我需要一些帮助。 我设计的程序给我第一个数字,然后跳过下一个数字,依此类推。但是每次遇到数字 8 时,结果都是 10 而不是 8,所以对于数字 9,结果将是 11。除了 8 和 9 之外的任何数字都不会发生这种情况。 经过多次尝试,我注意到当 sum1 达到 17 时重复同样的事情。如果您添加 1 或其他数字,它将跳过 18 和 19,并取值 20。 在我看来,好像程序是 1 2 3 4 5 6 7 10 11 12 13 14 15 16 17 20 21 22.
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int count = 8 ;
long number = 12345678 ;
long the_remainder ;
long sum1 = 0 ;
for (int i = 0 ; i < (count / 2) ; i++)
{
the_remainder = number % 10 ;
printf(" the_remainder is %lo\n", the_remainder);
number = number / 100 ;
sum1 = sum1 + the_remainder ;
printf("the sum is : %lo\n", sum1);
}
}
The result
%o
格式说明符以八进制格式输出,这就是值 8 显示为 10
的原因。
您想改用 %ld
,它以十进制打印。
您正在使用格式说明符 %o
,它将打印出 octal(即 base-8)整数。 base-8中显然没有数字8
或9
。
使用 %d
或 %ld
作为基数 10。
您应该尝试 %d
而不是 %o
。因为 %o
将打印八进制整数,而您预期的答案是以 10 为基数(十进制)。