Luhn算法的for循环中的未知值 [英] Unknown value in for loop for Luhn algorithm
本文介绍了Luhn算法的for循环中的未知值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这段代码,由于某些原因,我在for循环的每次迭代中都会得到非常多的数字,因此我无法弄清楚逻辑.
i have this code and for some reasons i get a very large number at every iteration of the for loop and i can't figure out the logic.
#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个):
Ok, so i enter the number 1234567890 and pass the do-while loop and when i enter the for loop i get these values (first 3 i display):
123456789
123456789
9
140443976194473(但我希望这是9)
140443976194473 (but i expect this to be 9)
推荐答案
您尚未初始化 sum.
.应将其定义为 long sum = 0;
或设置为 0
,然后再使用它.– 风向标
You have not initialised sum.
It should be defined as long sum = 0;
or set to 0
before you use it.
– Weather Vane
这篇关于Luhn算法的for循环中的未知值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文