输入中奇数位和偶数位的总和并进行比较。如果两者相等,则打印stat1,否则stat2

时间:2018-06-30 10:15:49

标签: c

这是代码,此代码不起作用。该程序需要使用for循环。我需要帮助才能完成这项工作。 程序为不同的数字打印相同的语句。请对此进行调试,并帮助我理解概念。

#include<stdio.h>
int main()
{
    int n,i,sum=0,sum1=0,rem;
    printf("enter values\n");
    scanf("%d",&n);

    for(i=n;i<=n;)
    {
        rem=n%10;
        if(rem%2 == 0)
        {
            sum=sum+rem;
        }
        else
        {
            sum1=sum1+rem;
        }
    n=n/10;
    }

if(sum==sum1)
    printf("I will win the Card Game");
else
    printf("I will not win the Card Game");

return 0;
}

3 个答案:

答案 0 :(得分:0)

#include<stdio.h>
int main()
{
    int n,i,sum=0,sum1=0,rem;

    printf("enter values\n");
    scanf("%d",&n);

    for(i = 0; i < n;)
    {
        rem=n%10;
        if(rem%2 == 0)
        {
            sum=sum+rem;
        }
        else
        {
            sum1=sum1+rem;
        }
        n=n/10;
    }

    if(sum==sum1)
        printf("I will win the Card Game\n");
    else
        printf("I will not win the Card Game\n");
    return 0;

}

答案 1 :(得分:0)

计算用户号码的长度,您将知道通过此循环获得的号码数量:

temp = n;
length = 0;
while (temp > 0) {
    length++;
    temp /= 10;
}

然后将此代码插入主循环之前,然后在主“ for”循环头中可以使用完整的“ for”语法:

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

全部放在一起:

int main()
{
    int n, i, sum = 0, sum1 = 0, rem, length, temp;

    printf("enter values\n");
    scanf("%d",&n);

    temp = n; // Temp variable to calculate digits' count
    length = 0; // Digits' counter
    while (temp > 0) { // Loop to calculate digits' count
        length++; // increase counter
        temp /= 10; // remove the unity digit, untill the number equal to 0.
    }

    for(i = 0; i < length; i++) // go through all digits
    {
        rem = n % 10;
        if(rem % 2 == 0)
        {
            sum = sum + rem;
        }
        else
        {
            sum1 = sum1 + rem;
        }
        n = n / 10;
    }

    if(sum == sum1)
        printf("I will win the Card Game, sum: %d", sum);
    else
        printf("I will not win the Card Game, sum: %d, sum1: %d", sum, sum1);
    return 0;

}

答案 2 :(得分:0)

尝试一下:

使用数组获取多个值,并按如下所示进行比较。

#include<stdio.h>
int main()
{
    int n,*arr,i,sum=0,sum1=0;

    printf("how many numbers\n");
    scanf("%d",&n); 

    printf("enter values");
    for(i=0;i<n;i++)
       {
        scanf("%d",&arr[i]);    
       }
    for(i=0;i<n;i++)
      {
       if(arr[i]%2 == 0)
          sum=sum+1;
      else
          sum1=sum1+1;

      }

if(sum==sum1)
    printf("I will win the Card Game");
else
    printf("I will not win the Card Game");
return 0;
}