为什么强数在代码中只显示一次?

时间:2019-01-14 14:01:38

标签: c

代码不会在给定的下限和上限范围内打印所有强数。它仅在打印1。找不到逻辑或语法错误。请帮忙。

C编程新手。在网上练习C题。问题是要打印所有强数。

int strong (int lower_limit,int upper_limit)
{
   int i,temp1,temp2,product=1,sum=0;

   for(i=lower_limit;i<=upper_limit;i++)
   {
      temp1=i;

      while(temp1!=0)
      {
         temp2=temp1%10;
         for( ;temp2>0;temp2--)
         {
            product=temp2*product;
         }
         temp1/=10;                
         sum=sum+product;
      }

      if(i==sum)
         printf("%d is a strong number\n",i);
   }

   return 0;
}

int main()
{
   int lower_limit,upper_limit;

   printf("Enter lower limit number\n");
   scanf("%d",&lower_limit);

   printf("Enter upper limit number\n");
   scanf("%d",&upper_limit);

   strong(lower_limit,upper_limit);

   return 0;
}

如果我将lower_limit设置为1,将upper_limit设置为1000,我应该得到1,2和145。

2 个答案:

答案 0 :(得分:3)

sumproduct永远不会重置。为避免此类情况,最好在实际需要的位置声明变量。否则,如果您忘记重置/更新值,则会得到临时状态

这应该有效:

int strong(int lower_limit, int upper_limit) {
    int i, temp1, temp2, product = 1, sum = 0;

    for (i = lower_limit; i <= upper_limit; i++) {
        temp1 = i;
        sum = 0; // should be reset when iterating through interval

        while (temp1 != 0) {
            temp2 = temp1 % 10;
            product = 1; // should reset for each digit
            for (; temp2 > 0; temp2--) {
                product = temp2 * product;
            }
            temp1 /= 10;
            sum = sum + product;
        }

        if (i == sum)
            printf("%d is a strong number\n", i);
    }

    return 0;
}

答案 1 :(得分:0)

int i ,rem ,num , fact=1, result=0;
int tempnum = num;

while(tempnum != 0)
{
    rem = tempnum % 10; // gives the remainder
    for(i=1;i<=rem;i++)
    {
        fact = fact * i;
    }
    result += fact;
    fact = 1; //to repeat the loop keeping fact as 1 because the value will change after every loop
    tempnum /= 10 ;
}