gpt4 book ai didi

c - Luhn 算法的 for 循环中的未知值

转载 作者:行者123 更新时间:2023-11-30 16:21:02 24 4
gpt4 key购买 nike

我有这段代码,由于某些原因,我在 for 循环的每次迭代中都会得到一个非常大的数字,但我无法弄清楚其中的逻辑。

#include <stdio.h>
#include <cs50.h>
#include <math.h>
#include <string.h>

int main(void)
{
long CARD, digits, digit, odd, sum;

// prompting the user for a positive card number and checking the length
do
{
CARD = get_long("Please insert your card number: ");
digits = floor(log10(labs(CARD)) + 1);
}
while (digits < 9 || digits > 16);

// Getting every other digit from the end (starting with the second to last)and adding the digits together
for (int i = 0; i < digits; i++)
{
CARD /= 10;
printf("%ld\n", CARD);
odd = CARD % 10;
printf("%ld\n", odd);
sum = sum + odd;
printf("%ld\n", sum);
CARD /= 10;
}
}

好的,所以我输入数字 1234567890 并传递 do-while 循环,当我进入 for 循环时,我得到这些值(显示前 3 个):

123456789

9

140443976194473(但我预计这是 9)

最佳答案

您尚未初始化sum。在使用之前应将其定义为long sum = 0;或设置为0。 – 风向标

关于c - Luhn 算法的 for 循环中的未知值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55006817/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com