如何使这个For循环在不进行初始化的情况下工作?

huangapple go评论78阅读模式
英文:

How can I make this For loop work without initializing it?

问题

public static int GetHalfDay(int Birthday) {
    int monthLength[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    int YearLength = 365;
    int HalfYear = 183;
    int HalfDay;
    int x = 1;

    if (Birthday >= 183) {
        HalfDay = Birthday - HalfYear;
    } else if (Birthday < 183) {
        HalfDay = Birthday + HalfYear;
    }

    for (int i = 0; x > 0; i++) {
        x = YearLength - monthLength[i];
    }

    return x;
}
英文:

I'm very very new and trying random easy stuff to get a grasp on my skills. This for loop is supposed to take how many days into the year your halfbirthday is, and figure out which month that day belongs to. Clunky I know but this is simply for practice. DaysIntoYear represents how many days into the year the persons actual birthday is.

The idea is to take the number of days into the year and one by one subtract out the length of all the months. When it gets below 0, we know that's the month I am looking for and I can take that int and pass it thru another function to get the String version of the month name. it wants me to initialize the variable Month but doing so breaks my equations. Initializing it as either 0 or 365 does not work. How can I make this work using just concepts laid out here? Again, I am very new and just trying to work with simple methods and for loops right now. But maybe a Do-While loop would work better? Let me know.

public static int GetHalfDay (int Birthday)
{
    int monthLength[] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
    int YearLength = 365; int HalfYear = 183;
    int HalfDay;
    int x = 1 ;
    
    if (Birthday &gt;= 183)
    {
        HalfDay = Birthday - HalfYear;
    }
    else if (Birthday &lt; 183)
    {
        HalfDay = Birthday + HalfYear;
    }
    
    for (int i=0; x &gt; 0 ; i++)
    {
        x = YearLength - monthLength[i];
        
    }
    
   return x; 
}

答案1

得分: 1

尝试这个:

public static int getHalfDay(int birthday) {
    int monthLength[] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
    int yearLength = (birthday + 183) % 365;
    int i;
    for (i = 1; yearLength > 0 ; i++) {
        yearLength -= monthLength[i];
    }
    return i - 1;
}

我建议使用调试器逐步执行它,以理解它的工作原理。

英文:

Try this:

public static int getHalfDay(int birthday) {
    int monthLength[] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
    int yearLength = (birthday + 183) % 365;
    int i;
    for (i = 1; yearLength &gt; 0 ; i++) {
        yearLength -= monthLength[i];
    }
    return i - 1;
}

I suggest stepping through it using a debugger to understand how it works.

huangapple
  • 本文由 发表于 2020年4月8日 13:09:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/61093713.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定