其实这道题是很简单的题目,给4个区间,计算添加多少重量可以让运费最低,我的思路大概就是得到输入所在的区间,判断现在需要多少运费和增加到下一个区间所需要的运费的大小。我的程序逻辑判断上面并没有问题,但是一提交到sicily就WA,找了很久都没找到答案,后来询问了大牛牛,才知道原来问题出现在while( cin )这个语句上,废话不多说,下面是修改过后AC的代码:
//注意输入流的判断问题!!!
#include <iostream>
#include <queue>
using namespace std;
struct fit
{
int weight;
int rate;
};
int main()
{
int number = 1;
int w, r;
while ( cin >> w )
{
cin >> r;
fit standar[4];
standar[0].weight = w;
standar[0].rate = r;
for ( int i = 1; i < 3; i++ )
{
cin >> standar[i].weight >> standar[i].rate;
}
cin >> standar[3].rate;
standar[3].weight = 1001;
int input;
queue<int> inputs;
while ( cin >> input && input != 0 )
{
inputs.push( input );
}
cout << "Set number " << number << ":" << endl;
while ( !inputs.empty() )
{
input = inputs.front();
inputs.pop();
int oprice, nprice;
int index;
//得到输入所在的区间
int i = 0;
for ( i = 0; i < 4; i++ )
{
if ( input <= standar[i].weight )
{
index = i;
break;
}
}
oprice = input * standar[index].rate;
//得到从index开始到最后的支出最少的价格
int tempPos = index;
int tempPrice = oprice;
for ( int j = index + 1; j < 4; j++ )
{
nprice = standar[j].rate * ( standar[j-1].weight + 1 );
if ( tempPrice > nprice )
{
tempPrice = nprice;
tempPos = j;
}
}
if ( tempPos != index )
{
cout << "Weight (" << input << ") has best price $" << tempPrice << " (add " << standar[tempPos-1].weight + 1 - input << " pounds)" << endl;
}
else
{
cout << "Weight (" << input << ") has best price $" << oprice << " (add 0 pounds)" << endl;
}
}
number++;
cout << endl;
}
return 0;
}
下面说一下为什么while( cin >> XXX )能过那道题,而while( cin )就不能过:
在C++里面,cin是一个istream>>是输入流的符号(相当于一个函数),实际上是istream >> ( istream &cin, Object &object),>> 会返回一个istream ,while(cin)是上次读入返回的输入流,不会是NULL,所以还是进入了while循环,如果你在main函数第一行加上输入重定向:freopen("in.txt","r",stdin); 然后把输入放到in.txt里面,就会多输出一个“Set Number... ”,而while( cin >> XXX )读到文件结尾,会返回NULL,从而退出while循环,不会多输出那一行set number...。