以下是我的代码。我的算法有问题。它显示输入文件中最大值和最小值的最后一个整数值。值。有人请看看,告诉我我做错了什么?
#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;
}
答案 0 :(得分:2)
您无条件地在每次迭代中将next
的值分配给largest
和smallest
:
while(instream>>next)
{
largest = next; // <-- Why are you surprised?
smallest = next; // <-- :)
if(largest<next)
{
largest = next;
}
if(smallest>next)
{
smallest = next;
}
}
答案 1 :(得分:2)
程序倾向于做他们被告知的事情。这就是你要做的事情:
while(instream>>next) {
largest = next;
smallest = next;
这是您始终将它们设置为最新的地方。也许改变这三行:
largest = 0;
smallest = –0;
while(instream>>next) {
答案 2 :(得分:1)
问题可能在这个循环中吗?
while(instream>>next)
{
largest = next;
smallest = next;
if(largest<next)
{
largest = next;
}
if(smallest>next)
{
smallest = next;
}
}
2 if语句是不可以访问的,因为最大和最小都等于next?如果while中的2个if语句永远不会执行,则每次迭代时,最大值和最小值将始终设置为next。
答案 3 :(得分: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;
}