我在C++中的搜索功能是提取所有答案,而不是一个答案

My search function in C++ is pulling up all the answers and not a single one

本文关键字:答案 一个 C++ 搜索 功能 提取 我在      更新时间:2023-10-16

我真的很困惑。我必须为一个班级制作这个实验室,我似乎不能让搜索只显示一个结果,而是显示一年中的所有月份。我似乎也无法弄清楚为什么当我在一年中输入 0 时它不显示总降雨量。谢谢。

#include <iostream>
#include <fstream>
const int MaxSize = 12; //How many weather lines will be available.
using namespace std;
struct WeatherInformation
{
    int Month;                            //Months of the year
    float TotalMonthsRainfall;            //Total amount of rainfall
    float HighTemp;                       //The Highest temperature of the month.
    float LowTemp;                        //The Lowest temperature of the month.
    float AverageTemp;                    //The Average temperature of the month.
};
WeatherInformation WeatherArray[MaxSize]; //Declaring a month array of MaxSize
void ReadFile(ifstream& MyinFile, WeatherInformation WeatherArray[]);
void WeatherMonthSearch (WeatherInformation WeatherArray[]);

int main()
{
    float TotalRainfall = 0;
    int count = 1;          //Counts how many times the for loop goes.
    int MonthOfWeather;     //User input of the month.
    char ProgramRedo;       //User input if they want to reuse the program.
    char exit_char;         //User input to exit the program.
    ifstream MyinFile;      //Variable that uses file.
    ReadFile (MyinFile, WeatherArray);       //Call ReadFile Function
    WeatherMonthSearch (WeatherArray);       //Call WeatherMonthSearch Function
    MyinFile.close(); //Closes file.
}
//Brett Holmes
//4/30/2013
//PreCondition:You need a file labeled weather.dat
//PostCondition: It puts the file variables into an array.
void ReadFile(ifstream& MyinFile, WeatherInformation WeatherArray[])
{
    float TotalRainfall = 0;
    char exit_char;
    int count = 0;
    int Month = 0;
    cout << "Your Weather Machine" << endl << endl;
    MyinFile.open("weather.dat");
    if (!MyinFile)
    {    //no
        cout << "Can't open input file." << endl; //Tests the right file.
        char exit_char;                         //End Program
        cout << "Press any key to exit" << endl;
        cin >> exit_char;
    }
    for(count = 1; count < MaxSize; count++) //Puts the file variables in the array.
    {
        WeatherArray[count].Month = WeatherArray[count].Month + 1;
        MyinFile >> WeatherArray[count].TotalMonthsRainfall;
        MyinFile >> WeatherArray[count].HighTemp;
        MyinFile >> WeatherArray[count].LowTemp;
        (WeatherArray[count].AverageTemp = ((WeatherArray[count].HighTemp + WeatherArray[count].LowTemp)/2));
        (TotalRainfall = TotalRainfall + WeatherArray[count].TotalMonthsRainfall);
    }
}
//Brett Holmes
//4/30/13
//PreCondition:You need to have the months already put into an array in a struct.
//PostCondition:Outputs the rainfall stats the user puts in then asks to run again.
//Outputs a error message if they type in the month wrong.
void WeatherMonthSearch (WeatherInformation WeatherArray[])
{
    float TotalRainfall;
    int months;
    int MonthOfWeather;
    char ProgramRedo;
    do
    {
        bool MonthFound = false;
        cout << "Please input the number of the Month. Ex. 1=Jan. 2=Feb. etc nn";
        cin >> MonthOfWeather;
        for(int i = 1; i <= MaxSize; i++)
        {
            months = WeatherArray[i].Month;
            if(months == MonthOfWeather ) //Finds the artist and outputs the results
            {
                cout << "nTotal Months Rainfall: " << WeatherArray[i].TotalMonthsRainfall << "   n";
                cout << "Highest Temperature: " << WeatherArray[i].HighTemp << "   n";
                cout << "Lowest Temperature: " << WeatherArray[i].LowTemp << "   n";
                cout << "Average Temperature: " << WeatherArray[i].AverageTemp << "   n";
                MonthOfWeather = true;
            }
        }
        if(MonthOfWeather == 0)
        {
            cout << "The total rainfall for the year is: " << TotalRainfall << ".";
        }
        if(MonthFound == false)
        {
            cout << "nMonth Number error. Month not found. Try again.nn";
            MonthOfWeather = false;
        }
        cout << "Would you like to look up another month of weather?n";
        cout << "Enter a 'Y' if yes and 'N' if no.n";
        cin >> ProgramRedo;
    }while(ProgramRedo == 'Y');
}

几个明显的问题:

  1. C++ 中的数组从 0 开始,因此您的 for 循环是逐个关闭的。在您的搜索功能中,for(int i = 1; i <= MaxSize; i++)for(int i = 0; i < MaxSize; i++) 。同样,在读取函数中,for(count = 1; count < MaxSize; count++)应该是for(count = 0; count < MaxSize; count++)的(如果要跳过索引 0,因为将其用作信号值,则应将 MaxSize 设置为 13,并使循环从 1 开始。

  2. 为什么要将布尔值分配给MonthOfWeather?你是说MonthFound吗?

  3. 您读取函数未正确设置月份。 如果使用从 1 开始的循环,则应WeatherArray[count].Month = count; WeatherArray[count].Month = WeatherArray[count].Month + 1;,如果循环从 0 开始,则应WeatherArray[count].Month = count + 1;

  4. 您在读取函数中计算了总降雨量,但结果存储在局部变量中,因此在读取完成后会丢失。要么将 TotalRainfall 设置为全局变量,要么在搜索函数中进行计算。

  5. 有很多冗余的变量定义:例如,您的天气数据数组是一个全局数组,因此没有理由实际传递它; exit_char 在读取函数中声明两次;main()的前五行声明了您从未使用过的变量。

此外,您的 read 函数实际上不会在失败时退出程序 - 它甚至仍然尝试从流中读取,然后调用您的搜索函数!如果需要错误检查,则应让 read 函数返回布尔值,并在调用搜索函数之前检查 read 函数是否成功,或者仅在该cin >> exit_char;之后调用 std::exit

因此,您遇到的一个问题是,您的局部变量出现在多个位置,但看起来您希望它们实际上包含相同的信息。

例如,我看到三种不同的TotalRainFall.一个在main中,它只是在那里,不用于任何东西,一个在ReadFile中计算,一个在WeatherMonthSearch中,它没有设置为任何东西。

我怀疑你希望这三个人都做点什么。实现这一点的一种方法是删除 ReadFileWeatherMonthSearch 中的本地,而是从 main 传入一个(作为对 ReadFile 的引用)。

还有一些地方可以在不初始化变量的情况下使用变量。养成初始化一切和无处不在的习惯!

在编译器中启用警告 - 如果您有任何形式或相当新的编译器(最近年份的gcc或MS Visual Studio),它应该至少告诉您其中的一些内容。

相关文章: