c - for 循环中的哪个变量的新用户输入

标签 c for-loop

我正在编写一个程序,该程序将数字作为输入,然后将它们相互比较以找到最低的数字。因为我不想这样做

printf("Enter a number: ");
scanf("%d", &a);

因为需要时间,所以我想用 for 循环来完成三次。我做了一个,但我知道它并不完美,因为它没有做我真正想要的事情。

我期望的是循环通过打印 printf 语句,将“a ”作为用户输入,再次打印该语句,现在将“b ”变量作为用户输入,完成循环后它将转到条件。

提前非常感谢:)

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

void min(){
    int a, b, c;

    for (int i = 1; i <= 3; i++){
        printf("Enter a number: ");
        scanf("%d %d %d", &a, &b, &c);
    }
    if (a < b && a < c){
        printf("This number: %d is the lowest one.\n", a);
    }
    else if (b < a && b < c){
        printf("This number: %d is the lowest one.\n", b);
    }
    else if (c < a && c < b){
        printf("This number: %d is the lowest one.\n", c);
    }
    else{
        printf("Error. You might have entered a floating point number or a character. Please check again\n");
     }
}

int main() {

     min();
     return 0;
}

最佳答案

不需要初始化3个变量。您可以使用临时变量并将其分配给数组索引。

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

void min(){
    int arr[3], temp;

    for (int i = 0; i <= 2; i++){
            printf("Enter a number: ");
            scanf("%d", &temp);
            arr[i]=temp;
    }

    if (arr[0] < arr[1] && arr[0] < arr[2]){
            printf("This number: %d is the lowest one.\n", arr[0]);
    }
    else if (arr[1] < arr[0] && arr[1] < arr[2]){
            printf("This number: %d is the lowest one.\n", arr[1]);
    }
    else if (arr[2] < arr[0] && arr[2] < arr[1]){
            printf("This number: %d is the lowest one.\n", arr[2]);
    }
    else{
            printf("Error. You might have entered a floating point number or a character. Please check again\n");
    }
}

int main() {
    min();
    return 0;
}

关于c - for 循环中的哪个变量的新用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58320914/

相关文章:

union 体可以在声明中初始化吗?

C程序未显示预期结果

c - 为什么多了一个数字?

c - 链表添加函数导致段错误

c - POSIX 读取 (2),意外行为

java - 如何使用for循环对变量进行计数?

java - 搜索对象问题

python - 如何将每一行对与前一列相关联?

tcp - 关于结构 tcp_info 的良好文档

java - 如何在循环外传递变量?