[英]How to make a value not increase greater than a maximum value in a progress bar
我正在嘗試制作一個程序,其中的值隨着按鈕的按下而增加,並且進度顯示在進度欄中。 最小值為0,最大值為100,我對其進行了編碼,因此,如果該值達到100以上,則使該值等於100。但是,它不斷超過100,並給我一個錯誤。 我是編程新手,不確定自己的錯誤在哪里。
if (happyLevel < 100)
{
happyLevel = happyLevel + 4;
}
else if (happyLevel > 100)
{
happyLevel = 100;
}
if (hungryLevel < 100)
{
hungryLevel = hungryLevel + 4;
}
else if (hungryLevel > 100)
{
hungryLevel = 100;
}
if (healthLevel < 100)
{
healthLevel = healthLevel + 4;
}
else if (healthLevel > 100)
{
healthLevel = 100;
}
您正在使用else if
檢查else if
,這意味着else if
變量中的數字大於96,則+ 4
可能會將任何變量增加到100以上。 一個快速的方法來解決它是去除所有else
之前的S if
這樣你做檢查不管秒。
如果其中一個級別是98,它將輸入與之相關的第一個if語句,並更新為102,而不輸入else if。 快速簡便的解決方法是將else if更改為if。
您不希望其他對象在那里。 您必須考慮如果將4設置為100以上,會發生什么情況:
if(happyLevel < 100)
happyLevel += 4;
if(happyLevel > 100)
happyLevel = 100;
附帶說明,該代碼也可以替換為:
happyLevel = Math.Min(100, happyLevel + 4);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.