1

目标是制作一个程序,当输入一系列数字时,会显示最小值和最大值。-99 将用作哨兵。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication12
{
    class Program
    {
        static void Main(string[] args)
        {
            double number = 0, maxValue = 0, minValue = 0;
            string goOn = "Y";

            Console.WriteLine("Please enter a series of numbers, when you wish to stop entering numbers please enter -99.");
            Console.WriteLine("The smallest and largest values will then be displayed.");
            Console.WriteLine("Remember not to enter -99 unless you want the series to end.");
            do
            {
                while (!double.TryParse(Console.ReadLine(), out number))
                    Console.WriteLine("Please enter whole numbers only");

                while (number != -99)
                {
                    process(ref number, ref minValue, ref maxValue);

                    while (!double.TryParse(Console.ReadLine(), out number))
                        Console.WriteLine("Please enter whole numbers only");
                }
                Console.WriteLine("The smallest value is {0} and the largest value is {1}.", minValue, maxValue);
                Console.WriteLine("Do you want to enter another series of numbers?");
                Console.WriteLine("If so enter y, if you want to end press any other key");
                goOn = Console.ReadLine();
                if (goOn.ToUpper() == "Y")
                {
                    Console.WriteLine("Please enter your set of numbers.");
                    Console.WriteLine("Remember not to enter -99 unless you want the series to end.");
                }

            } while (goOn.ToUpper() == "Y");
        }
        static void process(ref double minValue, ref double maxValue, ref double number)
        {

            if (number > maxValue)
            {
                number = maxValue;
            }
            if (number < minValue)
            {
                number = minValue;
            }

        }
    }
}

我还没有学习数组、气泡或类,但这里有一些问题:

可能是因为获取最小值和最大值的方法,如果我输入 3、22、7、15、1,我将得到 15 而不是 22,因为值 22 已被丢弃并替换为 7。

最小值未显示,而是显示为 0

当输入非数字时,显示错误信息后,再输入更多数字,则 minValue 显示与 maxValue 相同。

4

1 回答 1

6

这是一个简单的错误:

static void process(ref double minValue, ref double maxValue, ref double number)
    {

        if (number > maxValue)
        {
            maxValue = number;
        }
        if (number < minValue)
        {
            minValue = number;
        }

    }

您必须影响 maxValue 和 minValue,而不是数字。

于 2013-03-04T08:50:15.530 回答