C ++ while循环嵌套if语句

时间:2014-03-18 01:29:55

标签: c++ while-loop

嗨我在获取正确的最小值和正确的最大值时遇到了一些麻烦。我知道它与while循环有关。该计划的其余部分工作得很好。我找到了正确的平均值,总和和整数数

#include<iostream>
#include<fstream>

using namespace std;

int main()
{
    ifstream inputfile;

char choice;


int NumberOfIntegers = 0,
    SumOfIntegers = 0,
    Average = 0 ,
    LargestValue,
    SmallestValue,
    integer;

inputfile.open("random.txt");

if(!inputfile)
{
    cout << "the file could not be open" << endl;
}


inputfile >> integer;

//initialize smallest and largest
SmallestValue = integer;
LargestValue = integer;

while(inputfile)
{
    NumberOfIntegers++;
    SumOfIntegers = SumOfIntegers + integer;

    inputfile >> integer;
    if( integer >> LargestValue || integer << SmallestValue)
    {

        if ( integer >> LargestValue)
            LargestValue = integer;

        else 
            SmallestValue = integer;
    }
}

if(NumberOfIntegers > 0 )
{
    Average = SumOfIntegers / NumberOfIntegers;
}

do
{
    //Display Menu
    cout << "Make a selection from the list" << endl;
    cout << "A.   Get the largest Value" << endl;
    cout << "B.   Get the smallest Value" << endl;
    cout << "C.   Get the sum of the values" << endl;
    cout << "D.   Get the average of the values" << endl;
    cout << "E.   Get the number of values entered" << endl;
    cout << "F.   End this program" << endl << endl;

    cout << "Enter your choice -->  ";
    cin >> choice;

    cout << endl;

    switch (choice)
    {
    case 'a':
    case 'A': cout << "The largest value is " << LargestValue << endl;
        break;

    case 'b':
    case 'B': cout << "The smallest value is " << SmallestValue << endl;
        break;

    case 'c':
    case 'C': cout << "The sum of the values entered is " << SumOfIntegers << endl;
        break;

    case 'd':
    case 'D': cout << "The average of the values entered is " << Average << endl;
        break;

    case 'e':
    case 'E': cout << "The number of values entered is " << NumberOfIntegers << endl;
        break;

    case 'f':
    case 'F': cout << "Program is now ending" << endl;

        return 1;
        break;

    default: 
        cout << choice << " is an invalid value. " << endl;

    }

    cout << endl;

} while( choice != 'f' || choice != 'F');


return 0;

}

3 个答案:

答案 0 :(得分:2)

integer >> LargestValue

据推测应该是integer > LargestValue>>是一个轮班操作,而不是比较。这同样适用于<<

答案 1 :(得分:0)

你还应该确保将LargestValue初始化为小的,将SmallestValue初始化为大的值。否则,您可能会错过数据中的异常值。

答案 2 :(得分:0)

让你的“最大”&amp; “最小的”逻辑块是分开的 - 加入它们没有理由或正确性。

请注意,对于只包含一个项目的列表,该值将是最小最大。它不仅更复杂,而且使这些条件相互排斥是不正确的。

为变量使用更好的名称。使用“item”或“value”表示您当前正在阅读的内容,所有内容都是整数,因此实际上毫无意义。我更喜欢变量的小写首字母..已经在Java工作了一段时间:))

尽可能避免在具有有意义值的位置之前/之外声明变量。

int value;

inputfile >> value;
if (value > largestValue) {
    largestValue = value;
}
if (value > smallestValue) {
    smallestValue = value;
}

此外,您需要检测'first'或将smallest / largest初始化为+/- MaxInt以确保第一个值将被占用。

相关问题