-2

下面是我的代码。我的算法有问题。它显示输入文件中整数的最后一个最大值和最小值。价值观。有人可以看看并告诉我我做错了什么吗?

#include "cstdlib"
#include "iostream"
#include "fstream"

using namespace std;

int main()
{
    fstream instream;
    ofstream outstream;
    instream.open("num.txt");
    if(instream.fail())
    {
        cout<<"The input file failed to open\n";
        exit(1);
    }
    outstream.open("output.txt");
    if(outstream.fail())
    {
        cout<<"The output file failed to open";
        exit(1);
    }

    int next, largest, smallest;
    largest = 0;
    smallest = 0;

    while(instream>>next)
    {
        largest = next;
        smallest = next;
        if(largest<next)
        {
            largest = next;
        }
        if(smallest>next)
        {
            smallest = next;
        }
    }

    outstream<<"The largest number is: "<<largest<<endl;
    outstream<<"The smallest number is: "<<smallest<<endl;
    instream.close();
    outstream.close();
    return 0;
}
4

4 回答 4

2

您在每次迭代中无条件地分配nexttolargest和的值:smallest

while(instream>>next)
    {
        largest = next;    //  <--  Why are you surprised?
        smallest = next;   //  <--  :)
        if(largest<next)
        {
            largest = next;
        }
        if(smallest>next)
        {
            smallest = next;
        }
    }
于 2012-06-12T09:27:53.977 回答
2

程序倾向于按照他们被告知的去做。这是你告诉要做的:

while(instream>>next) {
        largest = next;
        smallest = next;

这是您始终将它们设置为最新的地方。也许将这三行更改为:

largest = 0;
smallest = –0;
while(instream>>next) {
于 2012-06-12T09:28:30.597 回答
1

问题可能出在这个循环中吗?

    while(instream>>next)

    {

    largest = next;

    smallest = next;

    if(largest<next)

    {

    largest = next;

    }

    if(smallest>next)

    {

      smallest = next;

    }

    }

由于最大和最小都等于下一个,因此无法访问 2 个 if 语句吗?如果 while 中的 2 个 if 语句从不执行,则每次迭代中最大和最小的将始终设置为 next。

于 2012-06-12T09:25:56.820 回答
0
#include<cstdlib>
#include<iostream>
#include<fstream>

using namespace std;

int main()
{
    fstream instream;
    ofstream outstream;
    instream.open("joy.txt");
    if(instream.fail())
    {
        cout<<"The input file failed to open\n";
        exit(1);
    }
    outstream.open("output.txt");
    if(outstream.fail())
    {
        cout<<"The output file failed to open";
        exit(1);
    }

    int next, largest, smallest;
    largest = 0;
    smallest = 0;


    while(instream>>next)
    {

        if(largest<next)
        {
            largest = next;
        }else{
                  smallest = next;
        }
    }

    outstream<<"The largest  number is: "<<largest<<endl;
    outstream<<"The smallest number is: "<<smallest<<endl;
    instream.close();
    outstream.close();

    system("pause");
    return 0;
}
于 2013-02-28T19:54:25.860 回答