【问题标题】:Issues on creating a while loop in C [duplicate]在 C 中创建 while 循环的问题 [重复]
【发布时间】:2017-09-19 19:02:27
【问题描述】:

我需要运行一个 while 循环来打印它的每一个结果,但不能让它正常工作。这是我取得的成就:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main ()
{
    float fahrenheit;
    int celsius;

    printf("Table of calsius degrees in fahrenheit 1-100:");
    celsius=0;
    fahrenheit=32;
    while (0 < celsius < 100)
    {
        celsius = (5.0 / 9.0) * (fahrenheit-32);

        fahrenheit = ((9.0 / 5.0) * celsius )+ 32;

        printf ("%f , %f\n", celsius,fahrenheit);
        celsius ++;
    }
    if (celsius>=101){
        printf("Jobs done");
    }
    return 0;

}

非常感谢任何帮助。目标是打印从 1 到 100 的每一个华氏温度和摄氏度。

【问题讨论】:

  • while (0 &lt; celsius &lt; 100) 这不是你想的那样。你的意思是while(celsius &gt; 0 &amp;&amp; celsius &lt; 100)
  • 正常工作是什么意思?它输出错误?是不是输出正确的结果?
  • 开启完整警告,你应该会看到类似comparison of constant 100 with boolean expression is always true
  • 另请注意:1)由于您将变量Celsius 初始化为0,因此您甚至都不会进入循环。 2)由于您每次都重新计算celsius,因此您可能会停止循环,因为您将失去精度并且最终不会四舍五入,最终会导致无限循环。
  • 即使那是正确的语法,你也永远不会进入循环。你将celsius 设置为0,所以0 &lt; celsius &lt; 100 第一次会是假的。

标签: c while-loop


【解决方案1】:

把条件写成这样

while ( celsius++ < 100)

并从循环中删除这些语句

celsius = (5.0 / 9.0) * (fahrenheit-32);

celsius ++;

循环结束后写就够了

printf("Jobs done");

没有 if 语句。

【讨论】:

  • 不知道为什么Celsius 在那里大写。
  • @tadman 我猜是自动更正。
  • 已修复,这很好。
  • @MatthiasNKR 完全没有。不客气。:)
猜你喜欢
  • 2016-03-22
  • 1970-01-01
  • 2017-08-11
  • 1970-01-01
  • 2017-06-02
  • 2018-07-20
  • 1970-01-01
  • 2014-11-08
  • 1970-01-01
相关资源
最近更新 更多