【问题标题】:I can't understand what's going wrong in this program [closed]我不明白这个程序出了什么问题[关闭]
【发布时间】:2017-08-28 11:14:20
【问题描述】:
#include<math.h>
#include<stdio.h>
int main(void)
{
    int i = 0;

    int f = 10000;

    int div1 = (powl(10,i));

    int temp1 =  f/div1;

    for(i = 2; temp1 > 1; i++)
    {
        printf("%i\n",temp1);
    }
}

据我所知,div1 的值应该是 100,1000,10000... 在 I 中有相应的增量。那么 temp1 应该是 100,10,然后循环停止(?)。但是我得到了 10000 10000 10000 10000 的无限循环......

谁能解释我做错了什么?

【问题讨论】:

  • 格式错误 + 缺少 {
  • for(i=2;temp1&gt;1;i++) 你的循环条件与i 无关,temp1 在循环中没有变化
  • 不是 temp1 = f/(powl(10/i));所以是 i 的函数,应该随 i 改变?
  • 那是 before 循环不在里面.. temp1 在初始值之后不会改变
  • 你真的需要了解一下 for 循环是如何工作的。我的建议是阅读一些 C 初学者教程

标签: c for-loop infinite-loop


【解决方案1】:

for 循环检查temp1,但temp1 在循环体中没有被修改。尝试将所需的修改放在循环体中或作为for 循环中的最后一个表达式;变量i 可能根本不需要。

【讨论】:

  • 这里可能有一些误解; temp1 = f/(powl(10/i)) 是一个只计算一次的表达式,对powl 执行一次调用。这不是一种神奇地链接temp1i 的方法,因为每次i 更改时它都会更改temp1,您可能会根据您在评论中使用的措辞假设。
【解决方案2】:

你的for 声明应该是这样的。您错过了在 for 循环中调用这些语句

    for(i = 2; temp1 > 1; i++)
    {
        div1 = (powl(10,i));

        temp1 =  f/div1;
        printf("%i\n",temp1);

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-12
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    相关资源
    最近更新 更多