英文:
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 >= 183)
{
HalfDay = Birthday - HalfYear;
}
else if (Birthday < 183)
{
HalfDay = Birthday + HalfYear;
}
for (int i=0; x > 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 > 0 ; i++) {
yearLength -= monthLength[i];
}
return i - 1;
}
I suggest stepping through it using a debugger to understand how it works.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论