c - 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.
解决方案
和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;
}
推荐阅读
- azerothcore - 路由器“ZXHN H168N V3.1”不能在Acore服务器的上下文中进行端口转发(这样做后,没有可见的开放端口)
- android - 如何在前台应用程序的任何活动中多次从服务中获取结果?
- javascript - 无法在单端口上运行反应应用程序和 java 后端
- c# - C# LINQ-to-XML 选择子元素属性最大的元素
- oracle - 在游标中选择查询 FOR LOOP
- ldap - 使用 PGAdmin 配置 LDAP
- python - 使用 pandas python 将列表导出到 csv 文件
- javascript - 如何使用 Helmet 4.4.1 版本 node.js 模块启用和禁用 upgradeInsecureRequests csp 指令
- amazon-s3 - 按用户限制 S3 HTTP 访问
- vba - 我的 excel vba 宏无法管理 ibm 大型机错误“响应模式事务终止而没有回复”