代码之家  ›  专栏  ›  技术社区  ›  Sundaze123

使用C,得到所有其他数字的总和

  •  -1
  • Sundaze123  · 技术社区  · 8 年前

    我试着做一个简单的程序,如果我输入-保持简单的事情-

    进来

    在屏幕上打印

    长度为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);
    }
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   cs95 abhishek58g    8 年前
    1. 你需要初始化 sum length 0 否则,它们会保留垃圾价值

    2. 接受输入的循环不正确。你需要

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

    3. 您需要交换这两条线,使其成为:

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

      迭代,数字将获得i+1 数字

    4. 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