C 程序 - While 循环

标签 c

嗨,我再次发现自己陷入了编码困境。我找到了正确的代码,但我不明白为什么我的初始编码不起作用。谁能简单解释一下这个问题吗?

我的初始代码和可运行的代码发布在下面。

初始代码(未按预期工作)

#include <stdio.h>
#include <conio.h>

int main(void)
{
   int counter;
   int num1, num2, smallest;

   counter = 1;

   printf("Enter first number:");
   scanf("%d", &num1);
   smallest = num1;

   while (counter <= 10) // User input phase
   {
      printf("Enter next numer:");
      scanf("%d", &num2);

      if (num1 < num2)
      {
         smallest = num1;
      }
      if (num2 < num1)
      {
         smallest = num2;
      }

      counter++;
   }

   printf("Smallest is %d", smallest);

   getch();
}

可运行的代码

#include <stdio.h>
#include <conio.h>

int main(void)

{
    int counter;
    int num1, smallest;

    counter = 1;


    printf("Enter first number:");
    scanf("%d", &num1);
    smallest = num1;

    while (counter <= 10) // User input phase
    {
        printf("Enter next numer:");
        scanf("%d", &num1);

        if (num1 < smallest)
        {
            smallest = num1;
        }
        if (smallest < num1)
        {
            smallest = smallest;
        }

            counter++;
    }

    printf("Smallest is %d", smallest);

    getch();
}

最佳答案

在第一次尝试中,您保存了每个循环中最小的值,但您将其删除,因为下一个循环将始终检查 num1num2 中新输入的数字>.

在第二个代码(工作代码)中,循环跟踪找到的最后一个最小的值。

一点小事,代码块

    if (num1 < smallest)
    {
        smallest = num1;
    }
    if (smallest < num1)
    {
        smallest = smallest;
    }

第二个if没有意义,可以这样写

    if (num1 < smallest)
    {
        smallest = num1;
    }
    else
    {
        smallest = smallest;
    }

或更好

    if (num1 < smallest)
    {
        smallest = num1;
    }

关于C 程序 - While 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32586959/

相关文章:

c - C 中的 abort() 函数是否清理堆栈?

c - 为什么我无法生成超过 1 个随机字符串?

c - 了解指针取消引用和数组索引之间的区别

使用 GNU make 启用分析功能来编译包

c - 通过调用共享 DLL 在两个线程之间进行信息交换

c - 将字符串数组附加到共享内存 - 段错误

c - assembly 局部变量和参数

c - 如何将 16 位值返回为 64 位值?

c - 何时谨慎使用 free() 来释放 malloc() 使用的内存?

c - 删除前导空格的函数不会更改调用者中的字符串?