C++ while循环嵌套if语句

标签 c++ while-loop

您好,我在获取正确的最小值和正确的最大值时遇到了一些问题。我知道这与 while 循环有关。该程序的其余部分效果很好。我找到了正确的 average , sum 和 number of integers

#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++ while循环嵌套if语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22468753/

相关文章:

c++ - 创建带有子窗口(控件)的分层窗口的策略

c++ - 我可以在 qt Creator 中使用带有 try catch 语句的断点吗?

c++ - 添加命名空间会删除对类私有(private)成员的好友访问权限

java - java while循环中多个条件的问题

php - FPDF - PHP While 循环只返回第一个值

c - 为什么当我在 C 程序的 while 循环中有 2 个 scanf 语句时,在 1 个循环之后只有其中一个会运行?

c++ - 什么操作可以使 float 离开 [0, 1] 范围?

c++ - {} 是传递给需要迭代器(代表某个容器的 std::end() )的函数的有效参数吗?

javascript - Three.js 为什么使用 for 循环而不是 while

c++ - 从没有空格的文本文件中读取数字