首页 > 解决方案 > Why is the strong number being displayed once in the code?

问题描述

The code is not printing all the strong numbers in the given range of lower limit and upper limit. It is only printing 1. Cannot find either logical or syntax error. Please help.

New to C programming. Was practicing C questions online. The question was about to print all the strong numbers.

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;
}

If I put lower_limit as 1 and upper_limit as 1000 I am supposed to get 1,2,and 145.

标签: c

解决方案


sum永远product不会重置。为了避免这种情况,最好在真正需要的地方声明变量。否则,如果您忘记重置/更新值,您最终会出现临时状态

这应该有效:

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;
}

推荐阅读