繁体   English   中英

谁能在C中为我简化这段代码?

[英]can anyone simplify this code for me in c?

n的所有奇数位数的总和(例如n为32677,总和为3 + 7 + 7 = 17)

这是代码。 对于此问题,任何循环或函数都是可以接受的,但不得超过此答案。

#include <stdio.h>
int main()
{
  char n[20];
  int m=0,i;
  printf("Enter integers for the variable n: ");
  for (i=0;i<20;i++)
  {
    scanf("%c",&n[i]);
    if(n[i]=='\n')
    {
      break;
    }
  }
  for (i=0;i<20;i++)// this is the part I would like to simplified
  {
    if (n[i]%2!=0)
    {
      if(n[i]==49)
      m++;
      if(n[i]==51)
      m+=3;
      if(n[i]==53)
      m+=5;
      if(n[i]==55)
      m+=7;
      else if(n[i]==57)
      m+=9;
    }
  }
  printf("The sum of odd digits of n is %d.",m);
}

以下是一些您可以使用的工具/想法:

  • 在ctype.h中有一个isdigit()函数,它告诉您字符是否代表数字。
  • 假设数字0..9的字符是顺序的,则由字符数字c表示的值是c-'0'

这个给你

#include <stdio.h>

int main( void )
{
    enum { N = 20 };
    char value[N];

    printf( "Enter an unsigned integer: " );

    size_t n = 0;

    for ( char digit; n < N && scanf( "%c", &digit ) == 1 && digit != '\n'; ++n ) 
    {
        value[n] = digit;
    }

    unsigned int sum = 0;

    for ( size_t i = 0; i < n; i++ )
    {
        if ( value[i] % 2 != 0 ) sum += value[i] - '0';
    }

    printf( "The sum of odd digits of the value is %u.\n", sum );
}

程序输出可能看起来像

Enter an unsigned integer: 0123456789
The sum of odd digits of the value is 25

或者,您可以添加检查以确保输入的字符是数字。 例如

#include <stdio.h>
#include <ctype.h>

int main( void )
{
    enum { N = 20 };
    char value[N];

    printf( "Enter an unsigned integer: " );

    size_t n = 0;

    for ( char digit; 
          n < N && scanf( "%c", &digit ) == 1 && isdigit( ( unsigned char )digit );
          ++n )
    {
        value[n] = digit;
    }

    unsigned int sum = 0;

    for ( size_t i = 0; i < n; i++ )
    {
        if ( value[i] % 2 != 0 ) sum += value[i] - '0';
    }

    printf( "The sum of odd digits of the value is %u\n", sum );
}

至于你的代码,那么在这个循环中

  for (i=0;i<20;i++)
  {
    scanf("%c",&n[i]);
    if(n[i]=='\n')
    {
      break;
    }
  }

您必须计算输入的位数。 并且换行符不得存储在数组中。 否则这个循环

  for (i=0;i<20;i++)

可能导致不确定的行为。

而且,您不应使用像49这样的幻数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM