-4

如果它符合算法,它应该有一个输出真,如果它不,输出应该是假的。知道哪里出错了吗?

我试过了

1586455534096 ; output : false(fail)

49927398716 ; output : true (ok)

984697300577 ; output : false (fail)

代码

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

int main()
{
  char str[100];
  int n,num[100],prod[100],remainder,sum,total;
  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]>=10)
            {
              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;
}
4

3 回答 3

3

你的代码工作。

#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;
}

在您的代码中有两个主要问题:

  1. 至少总 var 没有初始值
  2. 内部 while 必须>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;
}
于 2016-05-06T07:19:26.243 回答
0

乍一看total是未初始化的,代码中有未初始化的值会导致不确定的值

于 2016-05-06T06:53:01.577 回答
0

total在使用它之前你永远不会初始化,这意味着它的值是不确定的并且给你未定义的行为。可能与其他变量相同。

在声明时初始化变量,例如

int n, num[100] = { 0 }, prod[100] = { 0 }, remainder = 0, sum = 0,total = 0;
于 2016-05-06T06:53:08.650 回答