C Luhn算法有时工作有时失败
如果它符合算法,它的输出应该为true,如果不符合,则输出应该为false。知道哪里出了问题吗 我试过了C Luhn算法有时工作有时失败,c,algorithm,luhn,C,Algorithm,Luhn,如果它符合算法,它的输出应该为true,如果不符合,则输出应该为false。知道哪里出了问题吗 我试过了 1586455534096 ; output : false(fail) 49927398716 ; output : true (ok) 984697300577 ; output : false (fail) 代码 #包括 #包括 int main() { char-str[100]; int n,num[100],prod[100],余数,总和,总计; scanf(“%s”,st
1586455534096 ; output : false(fail)
49927398716 ; output : true (ok)
984697300577 ; output : false (fail)
代码
#包括
#包括
int main()
{
char-str[100];
int n,num[100],prod[100],余数,总和,总计;
scanf(“%s”,str);
对于(n=0;n=10)
{
剩余量=产品[n]%10;
总和=总和+余数;
产品[n]=产品[n]/10;
}
num[n]=总和;
}
总计=总计+数量[n];
}
如果(总计%10==0)
printf(“true\n”);
其他的
printf(“假”);
返回0;
}
乍一看,total
是未初始化的,并且在代码中有未初始化的值会导致不确定的值您在使用它之前从未初始化过total
,这意味着它的值是不确定的,并且会给您带来未定义的行为。可能与其他变量相同
在声明中初始化变量,例如
int n, num[100] = { 0 }, prod[100] = { 0 }, remainder = 0, sum = 0,total = 0;
你的代码正常工作
#include<stdio.h>
#include<string.h>
int main()
{
char str[100];
int n,num[100],prod[100],remainder,sum,total=0;
scanf("%s", str);
for(n=0;n<100;n++)
{
if(str[n]==0) break;
num[n] = str[n] - '0';
if(n%2!=0)
{
prod[n]=num[n]*2;
sum=0;
while(prod[n]>0)
{
remainder=prod[n]%10;
sum=sum+remainder;
prod[n]=prod[n]/10;
}
num[n]=sum;
}
total = total + num[n];
}
if(total%10==0)
printf("true\n");
else
printf("false\n");
return 0;
}
对不起,我不太明白。在进行任何计算之前,我是否将total=0?已尝试,但仍然失败。@M.H.F然后,您需要使用调试器逐行检查代码,同时监视变量和值,以查看何时何地出错。从您知道每个步骤中的值的一些输入开始,这样您就可以轻松地进行验证。我应该初始化total=0吗?您是否尝试过调试失败示例的代码?
#include<stdio.h>
#include<string.h>
int main()
{
char str[100];
int n,num[100],prod[100],remainder,sum,total=0;
scanf("%s", str);
for(n=0;n<100;n++)
{
if(str[n]==0) break;
num[n] = str[n] - '0';
if(n%2!=0)
{
prod[n]=num[n]*2;
sum=0;
while(prod[n]>0)
{
remainder=prod[n]%10;
sum=sum+remainder;
prod[n]=prod[n]/10;
}
num[n]=sum;
}
total = total + num[n];
}
if(total%10==0)
printf("true\n");
else
printf("false\n");
return 0;
}
#include<stdio.h>
#include<stdint.h>
#include<string.h>
int main()
{
char format[32];
char str[100]={0};
uint32_t n=0;
uint32_t num = 0;
uint32_t total=0;
snprintf(format, sizeof(format), "%%%zus", (sizeof(str)/sizeof(str[0]))-1 );
scanf(format, str);
while (str[n] != '\0')
{
num = str[n] - '0';
if(n%2!=0)
{
num*=2;
while(num>0)
{
total += num%10;
num/=10;
}
}
else
{
total += num;
}
n++;
}
if(total%10==0)
printf("true\n");
else
printf("false\n");
return 0;
}