[英]How can I make this For loop work without initializing it?
我很新,嘗試隨機簡單的東西來掌握我的技能。 這個 for 循環應該在你的半生日是一年中花費多少天,並找出那一天屬於哪個月份。 我知道笨重,但這只是為了練習。 DaysIntoYear 表示該人的實際生日一年中有多少天。
這個想法是將一年中的天數逐一減去所有月份的長度。 當它低於 0 時,我們知道這是我正在尋找的月份,我可以獲取該 int 並將其傳遞給另一個 function 以獲得月份名稱的字符串版本。 它希望我初始化變量 Month,但這樣做會破壞我的方程式。 將其初始化為 0 或 365 都不起作用。 我怎樣才能使用這里列出的概念來完成這項工作? 同樣,我很新,現在只是嘗試使用簡單的方法和 for 循環。 但也許 Do-While 循環會更好? 讓我知道。
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;
}
嘗試這個:
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;
}
我建議使用調試器逐步完成它以了解它是如何工作的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.