我必须请求用户输入 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/