c - 如何将用户输入与数组进行比较,检查它是否小于最后一个输入

标签 c arrays input compare

我必须请求用户输入 10 个不同的数字。我必须查看用户输入是否小于最后输入的数字(已添加到数组中)。我在比较它时遇到了麻烦,因为我的逻辑看起来很合理,但无论出于何种原因,它都不会在循环中保持较早输入的较低数字。大家可以看看我的if语句哪里出了问题。 getNum() 函数只是获取用户输入并在您好奇时返回它。提前致谢!

#include <stdio.h>   //including for the use of printf

/* == FUNCTION PROTOTYPES == */
int getNum(void);

/* === COMPILER DIRECTIVE - to ignore the sscanf() warning === */
#pragma warning(disable: 4996)


int main(void)
{   
// defining varibles
int myArray[11] = { 0 };
int counter = 0;
int indexTracker = -1;
int numInput = 0;
int lowestNum = 0;
int lowestNumPlace = 0;

// printing as to why I need 10 numbers
printf("I require a list of 10 numbers to save the world!\n");

// while loop
// while 'counter' is less than or equal to 9, loop
while (counter <= 9)
{
    // adding 1 to each varible, everytime the program loops
    indexTracker += 1;
    counter += 1;

    // printing to request a number, giving which number they are 
            // inputting
    // out of the list of 10
    // calling getNum() for input, saving the number into the array
    printf("Please enter a number for #%d: ", counter, "spot\n");
    numInput = getNum();
    myArray[indexTracker] = numInput;

    if (numInput <= myArray[indexTracker])
    {
        lowestNum = numInput;
        lowestNumPlace = indexTracker;
    }
}
// printing the lowest value and its index
printf("The lowest number is: %d at index [%d].", lowestNum, 
lowestNumPlace);

return 0;
}

最佳答案

您总是为 lowestNum 分配一个新值

numInput = getNum();
myArray[indexTracker] = numInput;

if (numInput <= myArray[indexTracker])
{
    lowestNum = numInput;
    lowestNumPlace = indexTracker;
}

...因为在执行 A=B 之后,B<=A 在逻辑上将始终为真。

试试这个:

numInput = getNum();
myArray[indexTracker] = numInput;

if (numInput <= lowestNum)  // note, comparing to the lowest number, not the current one
{
    lowestNum = numInput;
    lowestNumPlace = indexTracker;
}

关于c - 如何将用户输入与数组进行比较,检查它是否小于最后一个输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54753345/

相关文章:

c# - 如何在 .NET 3 控制台应用程序的打印行中间获取输入

vb.net - 在 VB.net 中逐行读取文本框的最佳方法

java - 如何在 cs50 第一题中获取用户的输入?

c - 有没有办法更好地路由流程?

c - 将二维数组从 Fortran 传递到 C

c - 如何编译内核模块

对字符串指针数组的打印过程感到困惑

javascript - 使用 Javascript/Jquery 将文本字段转换为数组并显示在页面上

c - 在没有 MAX_ELEMENTS 的情况下初始化数组是否更好?

java - 为什么我不调用 readLine() 时仍然可以在控制台中输入?