使用C,得到每隔一位完全不工作的数字的总和

von4xj4u  于 2023-01-12  发布在  其他
关注(0)|答案(2)|浏览(111)

我在试着做一个简单的程序如果我输入-为了简化-
进入
5235
屏幕打印输出
长度为4
总和是8
进入
54468
打印
长度为5
总和是10
然而,只有长度似乎是工作,我不知道为什么。
我得到了用户输入的数字的总长度,并指定如果数字是奇数,则添加偶数计数,反之亦然,但它似乎没有工作。

#include <stdio.h>
#include <cs50.h>
int main(void)
{
  long long cc_number;
  long long x;
  long long length;
  int sum, count = 0;

  do
  {
    printf("Please Enter Credit Card Number ");
    cc_number= get_long_long();
    x= cc_number;
  }
  while (x>0);

  while (x != 0)
  {
    x= x/10;
    length++;
  }

  x= cc_number;

  while (x != 0)
  {
    x= x/10;
    int digit= (int) (x % 10);
    count++;
    if ((count % 2 == 0) && (length %2 ==1))
    {
      sum=sum+digit;
    }
    else ((count % 2 == 1) && (length %2 ==0))
    {
      sum=sum+digit;
    }
  }

  printf("the sum is %i", sum);
  printf("the length of the digits is %lli", length);
}
w6lpcovy

w6lpcovy1#

1.您需要将sumlength初始化为0。否则,它们将保留垃圾值
1.接受输入的循环不正确。您需要

do {

...} while (x <= 0);

否则将无限循环。
1.您需要将这两条线互换,使其变为:

int digit = (int) (x % 10);
x = x/10;

否则,在第i次迭代中,digit将获得第i+1位,而不是第i位。

  1. else (...)是无效语法。您需要else if (...)
    完整列表:
#include <stdio.h>
int main(void)
{
  long long cc_number;
  long long x;
  long long length = 0;
  int sum = 0, count = 0;

  cc_number = (x = 54560);

  while (x != 0)
  {
    x= x/10;
    length++;
  }

  x= cc_number;

  while (x != 0)
  {
    x= x/10;
    int digit= (int) (x % 10);
    count++;
    if ((count % 2 == 0) && (length %2 ==1))
    {
      sum=sum+digit;
    }
    else if((count % 2 == 1) && (length %2 ==0))
    {
      sum=sum+digit;
    }
  }

  printf("The sum is %i\n", sum);
  printf("The length of the digits is %lli\n", length);
}

这个打印出来

$ ./a.out   
The sum is 10
The length of the digits is 5

(我对print语句做了一些修改。)

iezvtpos

iezvtpos2#

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

int main(void)

{
    long long length = 0;
    int sum = 0, count = 0;
    long long cc_number;
    long long a = get_long("Please Enter Credit Card Number ");

    cc_number = a;

  while (a != 0)
  {
    a= a/10;
    length++;
  }

  a = cc_number;

  while (a != 0)
{
    int digit= a % 10;
    a= a/10;
    count++;

    if (count % 2 == 0)
    {
      sum=sum+digit;
    }
}

  if (sum % 2 == 0)
  {
    printf("СС Number %lli\n", cc_number);
  }

  if ((count == 15) && (cc_number / 10000000000000 == 37 || cc_number / 10000000000000 == 34  ))
  {
    printf("American Express\n");
  }

  if ((count == 16) && (cc_number / 100000000000000 == 51))
  {
    printf("MarsterCard\n");
  }

  else
  {
    printf("INVALID\n");
  }
}

相关问题