编写一个程序,读取txt文件,将值输入向量,然后确定低于冻结值的值(温度)的数量。我的结果一直是0,无法弄清楚我的错。任何帮助将不胜感激!
下面是实际分配的问题和到目前为止的代码 编写一个主程序,询问用户文件名。该文件包含每日温度(整数)。
主调用这两个函数来(1)在矢量中存储温度(2)显示冻结温度(<= 32o F)的天数。
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
using namespace std;
//prototypes
void readTemperaturesFromFile(vector<int>& V, ifstream&);
int countFreezingTemperatures(vector<int>& V);
int main()
{
ifstream ins;
string fileName;
int totalFreezing = 0;
vector<int> temperature;
cout << "Please enter the name of the file: ";
cin >> fileName;
ins.open(fileName.c_str());
readTemperaturesFromFile(temperature, ins);
totalFreezing = countFreezingTemperatures(temperature);
cout << "Total number of days with freezing temperature: " << totalFreezing <<
endl;
ins.close();
system("pause");
return 0;
}
// The function reads temperatures (integers) from a text file and adds
// pushes them to the vector. The number of integers in the file is
// unknown
void readTemperaturesFromFile(vector<int> &V, ifstream& ins)
{
int temperature, v;
while (ins >> v)
{
V.push_back(v);
}
}
// The function returns the number of freezing temperatures (<=32oF)
// in the vector.
// You need to consider the case where the vector is empty
int countFreezingTemperatures(vector<int>& V)
{
int counter = 0;
if (V.empty());
cout << "empty" << endl;
for (int i = 0; i < V.size(); i++)
if (V[i] <= 32)
{
return counter;
counter++;
}
}
答案 0 :(得分:0)
您需要更改countFreezingTemperatures
功能
;
之后没有多余的if
您应该计算所有温度<=32oF
,然后返回counter
int countFreezingTemperatures(vector<int>& V)
{
int counter = 0;
if (V.empty())
{
cout << "empty" << endl;
}
else
{
for (int i = 0; i < V.size(); i++)
{
if (V[i] <= 32)
{
counter++;
}
}
}
return counter;
}
答案 1 :(得分:0)
您的 countFreezingTemperature 实现返回0。看看:
for (int i = 0; i < V.size(); i++)
if (V[i] <= 32)
{
return counter;
counter++;
}
}
此代码说的是“立即达到等于或低于32的温度时,返回计数器”(设置为0)。
这里是解决方法:
for (int i = 0; i < V.size(); i++)
if (V[i] <= 32)
{
counter++;
}
}
return counter;