簡體   English   中英

詢問用戶輸入和命令以繼續或停止。 用戶希望程序停止后,它會向用戶提供程序期間輸入的最大值和最小值?

[英]Ask user input and a command to continue or stop. After user wants program to stop, it give user the max and min value entered during the program?

問題和例子

我正在嘗試編寫一個程序,要求用戶輸入一個數字,然后詢問用戶是否要繼續。 如果響應為“是”,則程序將再次要求用戶輸入。 如果響應為“否”,則程序將停止並向用戶提供用戶在程序運行期間輸入的最大值和最小值。

這是我對這個問題的看法,它仍然不完整而且可能是非常錯誤的

#include <stdio.h>

int main()
{
    float value, command, max, min;
    int a[100];
    
    printf("Please enter the value: ");
    scanf("%f",value);
    
    printf("Do you want to continue?: ");
    scanf("%f",command);
    
    if (!strcmp(command, "yes")){
    printf("Please enter the value: ");
    scanf("%f",value);
    printf("Do you want to continue?: ");
    scanf("%f",command);    
    }
    
    if (!strcmp(command, "no")){
    max = a[0];
    min = a[0];

    for(int i=1; i<n; i++)
    {
        if(a[i]>max)
        {
            max = a[i];
        }


        if(a[i]<min)
        {
            min = a[i];
        }
    }
    } 
    
    printf("The maximum value is %f, and the minumum is %f",max,min);
    
    return 0;
}
  • 要處理任意數量的輸入,請使用循環並測試新的最小值和最大值。
  • scanf轉換規范%f需要value的地址。
  • 我們不能將command字符串掃描成float
  • 我們使用printf轉換規范%g獲得的數字的給定 output 格式。

例如:

#include <float.h>
#include <stdio.h>
#include <string.h>

int main()
{
    float value, max = FLT_MIN, min = FLT_MAX;
    char command[4];
    do
    {
        printf("Please enter the value : "); scanf("%f", &value);
        if (value > max) max = value;
        if (value < min) min = value;
        printf("Do you want to continue : "); scanf("%3s", command);
    } while (strcmp(command, "no") != 0);
    printf("The maximum value was %g and the minumum is %g\n", max, min);
}

請注意,示例代碼對於錯誤輸入是不安全的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM