C程序,从涉及精确小数的用户输入中打印出最大值和最小值

时间:2018-10-23 16:45:13

标签: c

我是一名新手程序员,刚开始自学C语言,然后决定解决一些来自Internet的简单问题。具体来说就是: Problem

我的解决方法是:

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

int main() {
    double min = DBL_MAX;
    double max = DBL_MIN;
    double n;

    do {
        scanf("%lf", &n);

        if (n < 0.0001) {
            break;
        }

        if (n > max) {
            max = n;
        }

        if (n < min) {
            min = n;
        }
    } while (n > 0.0000);

    printf("Min: %.4f Max: %.4f\n", min, max);
    return 0;
}

但是,我需要完全按照problem指定的输入/输出运行程序。 例如,考虑我在不同的行中输入:

1.1 1.2 1.3 3 6 9 11 -2 7
2.2
2.3 12
0

程序应将12输出为max,将-2输出为min,当输入0时,程序结束。

3 个答案:

答案 0 :(得分:2)

您需要将最小和最大BOTH设置为scanf设置的第一个值,然后检查大于或小于以后的迭代。现在它的工作方式是,min从0开始,并且永远不会改变,因为没有什么可以低于该值而无需退出程序。

int main(){
  double min = 0; 
  double max = 0; 
  float n; 
  int count = 0; 

  do{
    scanf("%f", &n);

    if(n < 0.0001){
      break;
    }  
    if( count ) {
        if(n > max){
            max = n; 

        } else if(n < min){
            min = n; 
        }  
    } else {
        max = n; 
        min = n; 
        count = 1; 
    }  

  }while(n > 0); 

  printf("Min: %.4f Max: %.4f\n", min, max);

  return 0; 
}

此外,浮点数的正确类型是%f。

答案 1 :(得分:0)

确保您再次阅读问题描述,与尝试的内容相比,代码中的逻辑被污染了。

根据问题描述,n可以是一个整数,因为您使用它来定义要赋予程序的值的数量。

然后可以使用for循环(for(i=0; i < n; i++){CODE HERE})来收集用户的更多输入。给定的第一个数字应该是minmax值的基值。

获得基本值后,可以将minmax与之后的每个输入进行比较。 (即if(max < input) {max = input}if(min > input) {min = input}

如果您还有其他问题,欢迎随时与我联系,我会尽力帮助您解决问题:)

答案 2 :(得分:0)

  1. 使用math.h可以使用INFINITY和-INFINITY。 http://pubs.opengroup.org/onlinepubs/007904975/basedefs/math.h.html
  2. 将双打与文字进行比较以便做出决定充其量是棘手的。此外,程序中最好有正数和负数。
  3. fflush(stdin)删除了缓冲区中以前的所有输入。
  4. 请注意,最大值从-INFINITY开始,而最小值从+ INFINITY开始。
  5. 将浮点数与双精度型进行比较将始终导致使用双精度型执行计算。尽量不要将它们混为一谈。

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

int main()
{
    double min = +INFINITY;
    double max = -INFINITY;
    double n;
    char ans = 'n';

    do
    {
        printf("Enter a number: ");
        scanf("%lf", &n);

        if(n > max)
        {
            max = n;
        }

        if(n < min)
        {
            min = n;
        }
        fflush(stdin);  // gets rid of previous input
        printf("Another number? (y/n): ");
        scanf("%c", &ans);
    }
    while(ans == 'y');

    printf("Min: %.4f Max: %.4f\n", min, max);
    return 0;
}

输出:

Enter a number: -45.6
Another number? (y/n): y
Enter a number: 23.0
Another number? (y/n): y
Enter a number: 92.3
Another number? (y/n): y
Enter a number: -100.22
Another number? (y/n): n
Min: -100.2200 Max: 92.3000

Process returned 0 (0x0)   execution time : 15.805 s
Press any key to continue.