前往
大廳
主題

【C#練習】 訂閱提醒,使用兩個 if 陳述式來實作(Microsoft Learn的練習題)

小村 | 2022-12-02 10:47:41 | 巴幣 0 | 人氣 413

【題目】
Random random = new Random();
int daysUntilExpiration = random.Next(12);
int discountPercentage = 0;
// Your code goes here

使用兩個 if 陳述式來實作下列業務規則 (若為陳述式,於第一項使用三個分支或巢狀)

規則 1。 如果使用者的訂閱方案將在 10 天或更少天數內到期,則顯示下列訊息:
輸出
Your subscription will expire soon. Renew now!
規則 2。 如果使用者的訂閱將在 5 天或更少天數內到期,則顯示下列訊息:
輸出
Your subscription expires in x days.
Renew now and save 10%!
請務必以 x 取代變數中儲存的值。
規則 3。 如果使用者的訂閱將在 1 天內到期,則顯示下列訊息:
輸出
Your subscription expires within a day!
Renew now and save 20%!
規則 4。 如果使用者的訂閱方案已過期,則顯示下列訊息:
輸出
Your subscription has expired.
規則 5。 如果使用者的訂閱方案將在超過 10 天後到期,則不顯示任何訊息。
【Solution】
Random random = new Random();
int daysUntilExpiration = random.Next(12);
int discountPercentage = 0;

// Your code goes here
if(daysUntilExpiration == 0)
{
Console.WriteLine("Your subscription has expired.");
}
else if(daysUntilExpiration == 1)
{
Console.WriteLine("Your subscription expires within a day!");
discountPercentage = 20;
}
else if (daysUntilExpiration <= 5)
{
    Console.WriteLine($"Your subscription expires in {daysUntilExpiration} days.");
    discountPercentage = 10;
}
else if (daysUntilExpiration <= 10)
{
    Console.WriteLine("Your subscription will expire soon. Renew now!");
}

if (discountPercentage > 0)
{
    Console.WriteLine($"Renew now and save {discountPercentage}%.");
}

創作回應

追蹤 創作集

作者相關創作

更多創作