c - 为什么这个程序一直显示结果?

标签 c

<分区>

我编写了这个程序,它将输入的高度(以厘米为单位)更改为英尺和英寸。当我运行它时,结果不停地出现。有谁知道为什么?

#include <stdio.h>

int main (void)
{
  float heightcm;
  float feet;
  float inch;

  printf("Enter height in centimeters to convert \n");
  scanf("%f", &heightcm);

  while (heightcm > 0)
  {
   feet = heightcm*0.033;
   inch = heightcm*0.394;

   printf("\n %0.1f cm = %0.2f feet and %0.2f inches \n", heightcm,feet,inch);
  }
 return 0;
}

最佳答案

你做了一个无限循环:

  while (heightcm > 0)   // if user enters a height > 0 we get in
  {
   feet = heightcm*0.033; // update feet 
   inch = heightcm*0.394; // update inches

   // print the result
   printf("\n %0.1f cm = %0.2f feet and %0.2f inches \n", heightcm,feet,inch); 
  }

循环中的任何地方 heightcm 都没有改变,这意味着它总是 > 0 并且您的函数将永远循环并且永远不会终止。 if 检查在这里更有意义:

  if (heightcm > 0)   // if user enters a height > 0 we get in
  {
   feet = heightcm*0.033; // update feet 
   ...

或者您可以使用 while 循环并不断请求更多输入:

  while (heightcm > 0)
  {
    printf("Enter height in centimeters to convert \n");
    scanf("%f", &heightcm);
    ...

这可能是您想要的(循环直到用户输入一个非正数)

关于c - 为什么这个程序一直显示结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13589720/

相关文章:

c - 通过引用传递并将值赋给结构指针的指针

c - 如何理解大输入的递归函数调用

C - 如何找到结构的大小?

c - 从 Linux 应用程序执行相当于 chattr +i filename.txt 的操作

c - 在arduino中什么是SREG?

c - 字符串出现异常错误

c++ - 无法打开源文件 "limits"

c - 将字符串传递给 main 并分解为数组

c - 打印多个整数输出 0

c - 为什么这个矩阵初始化为 2x4 而不是 2x2?