程序中for循环的逻辑错误,意外结果

时间:2013-04-17 17:37:05

标签: c++ for-loop

我有这个程序可以找到epochT秒的日期和月份。我将发布代码并解释发生的意外情况。我确定它与代码中的for循环有关,但我会更详细地解释。我也想与处理类似问题的人分享我的算法,但我需要它先工作哈哈。

#include <curses.h>
#include <sys/time.h>
#include <time.h>
#include "fmttime.h"                    // Include for formattime interface
#include <strstream>
#include <iostream>
#include <iomanip>


static int monthindex;                  // Lookup table index
static const int milli = 1000;          // Constant value for ms conversion
static const int epochyear = 1970;      // Epoch year 1970
static const int leapy = 4;             // Number of years for a leapyear
using namespace std;


struct Monthpairs                       // Fields for month & day lookup table
{
    const char* mon;                    // Months
    int day;                            // Days
};


Monthpairs months[] =                   // Lookup table for months & days
{
    {"Jan", 31},
    {"Feb", 28},
    {"Mar", 31},
    {"Apr", 30},
    {"May", 31},
    {"Jun", 30},
    {"Jul", 31},
    {"Aug", 31},
    {"Sep", 30},
    {"Oct", 31},
    {"Nov", 30},
    {"Dec", 31},
};


// Structure which will contain the human readable local
// time values
struct ExpandedTime
{


    int et_usec;        // Number of Milliseconds local time
    int et_sec;         // Number of Seconds local time
    int et_min;         // Number of minutes local time
    int et_hour;        // Number of hours local time
    int et_day;         // Day of the month local time
    int et_mon;         // Month of the year local time
    int et_year;        // Our current year (2013 present)


};


// Function prototype for Expanded time function


ExpandedTime* localTime(struct timeval* tv, ExpandedTime* etime);


// Expanded time will take the Epoch time and convert into days,
// months years, hours, minutes etc and then store this back into
// the Expanded Structure


ExpandedTime* localTime(
                        struct timeval* tv,     // Pointer to timeval struct
                        ExpandedTime* etime     // '' '' to expandedtime strct
                        )
{
    tzset();                                    // Corrects for timezone


    int epochT = (tv->tv_sec) - timezone;       // Epoch seconds with
    int epochUT = tv->tv_usec;                  // epochtime microseconds
    int edays;                                  // Days since epochtime
    int days4years = 1461;                      // Number of days in 4 years
    int fouryears;                              // Number of 4 year periods
    int remaindays;                             // Number of days leftover
    int tempdays;                               // Holds value of remaindays
    int monthtracker;                           // Number of TOTAL months passed
                                                // since current 4 year period
    int daysgoneby;                             // Number of days passed
                                                // since current 4 year period


    etime->et_usec = (epochUT/milli) % milli;   // Find the milliseconds


    etime->et_sec = epochT % 60;
    epochT /= 60;                               // Turn into minutes


    etime->et_min = epochT % 60;
    epochT /= 60;                               // Turn into hours


    if (localtime(&tv->tv_sec)->tm_isdst !=0)
        etime->et_hour = (epochT % 24) + 1;     // Hours with DST correction
    else
        etime->et_hour = (epochT % 24);


    edays = tv->tv_sec / 86400;                 // Turn into days since epochT




    fouryears = edays / days4years;
    remaindays = edays % days4years;            // Determines which 4 year perio
    tempdays = remaindays;


    for (monthindex = 0 ; tempdays > 0 ; monthindex++)
    {
        daysgoneby += months[monthindex].day;   // Keeps track of days passed


        tempdays -= months[monthindex].day;


        if (monthindex >= 11)                    // Resets counter for 12 months
        {
            monthindex = 0;
        }
        ++monthtracker;
    }
    etime->et_day = tempdays + months[monthindex].day;


// This will take the number of months passed in current 4 year period
// and add it to the epoch year of 1970 to find the current year


    etime->et_year = (monthtracker / 12)  + (fouryears * 4) + epochyear;
    return etime;


}


// Formats epoch time passed from a main function to a
// human readable string


char* formatTime(
                struct timeval* tv,     // Pointer to timeval struct
                char* buf,              // Pointer to char buf
                size_t len              // size of buffer
                )
{
    struct ExpandedTime etime2;         // Struct object declaration




    // Array containing strings for the months


/*    const char* month[] =
        {NOT USED OLD CODE BUT LEFT IN JUST IN CASE
        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
        "Aug", "Sep", "Oct", "Nov", "Dec"
        };*/




    if (len > 0)                        // Will only print to valid sized buffer
    {
        localTime(tv, &etime2);
        ostrstream oss(buf, len);


        // Prints the time and date into a human readable string and
        // places it in the supplied buffer from plot.cc


        oss << etime2.et_year << " " <<  months[monthindex].mon << " " <<
        etime2.et_day << " " << setw(2) << etime2.et_hour << ":"
        << setfill('0') << setw(2) << etime2.et_min << ":" << setfill('0')
        << setw(2) << etime2.et_sec << ":" << setfill('0') << setw(3) <<
         etime2.et_usec << ends;
    }


    else if (len <= 0)
    {
        cout << "Sorry the length of the buffer is too small cannot write" << en
    }


    return buf;
}

所以继续我遇到的错误。在for循环中,“tempdays”出现了一些非常大的负值,就像我的“monthtracker”变量一样。我不知道这是怎么发生的。我每次循环运行时都将monthtracker递增1,并且我在进入循环之前检查了Tempdays,它有一个值= remaindays,它是1202.所以不知何故,这个值变为负数,这可以预期,但是它的大小数字似乎没有意义..

我试图实现的逻辑是,我可以找到自大纪元1970年1月1日以来已过去多少4年。从那以后,我可以找到剩余的剩余天数,这些天数不适合4年。使用该值,我遍历我的查找表months []并减去每个月的天数,直到临时值为0或小于0.我然后添加回“monthindex”中的哪个月停止查找当前日期。然而,在for循环之后,月度跟踪和临时问题的上述问题让我头疼不已。哦,在forloop里面,我一旦点击11就重置了monthindex计数器,因为我的查询表中只有12个月(因为应该有lol)。

编辑代码已编辑为更正。

0 个答案:

没有答案