0

この問題を理解するのに苦労しています。コードは非常に基本的なものですが、予想外の動作をします。このコードは、日次データベースから毎月 15 日のデータを抽出して別のファイルに保存するルーチンの簡易バージョンです。問題はどこだ ?最初の cout は、入力された外側の任意の日の数を出力します。次に、適切な日を選択するための条件行がいくつかあります (この例ではそれほど重要ではありません)。次に、15 日のデータを新しいファイルに出力するブロック (内側の if) があります。さて、ご覧のとおり、外側のループ (注意!) は 10 番目にのみ入力されますが (これは既に間違っています - 11 から 15 までのすべての数字を書き込む必要があります)、ファイルが書き込まれたことも出力されます。 15日!問題はどこだ ?OUTER IFは10日のみエントリーし、

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;


int main()
{
    string newdata="mamma";
    string risultato="-";
    string PriorLine="-";
    int PriorDay=0;
    int lastmonth=0;

        // Loops through all the months
        for (int mese=1; mese <=12; mese++)
        { 
            //Loops through all the days in the month
            for(int day=1; day<=30; day++)
            {
                // at the month's beginning these 2 strings are set ="-"
                if (mese != lastmonth)
                {
                 risultato="-";
                 PriorLine="-";
                 }
                // if we are between the 10th and the 20th and the result is still to be found
                if (day>=10 && day<=20 && risultato=="-")
                {   
                       cout << day << endl;  // LISTS ALL THE DAYS THIS LOOP IS ENTERED
                       if (day=15)  // if it is exactly day 15 print that day's result
                              risultato=newdata;    
                       // if that month in the data there is no day 15 and 
                       // this is the second pass, choose the closest !  
                       if (day>15 && PriorLine !="-")
                       {
                            if (abs(day-15)<=abs(15-PriorDay))
                                   risultato=newdata;
                            else
                                   risultato=PriorLine;
                        }
                        PriorLine=newdata;
                        PriorDay=day;
                        if (risultato != "-")
                        {   
                            // writes the result ( risultato ) in a file
                            cout << "file written on the " << day << endl;

                         }
                 }                  
                 lastmonth=mese;
           }
    }    
    system("pause");
    return 0;

}

4

2 に答える 2