嗨,我在获取正确的最小值和正确的最大值时遇到了一些麻烦。我知道这与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;
}
最佳答案
integer >> LargestValue
大概应该是
integer > LargestValue
。 >>
是移位操作,不是比较。 <<
同样。关于c++ - C++ while循环嵌套if语句,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22468753/