如果用户必须输入整数,如何在我的 if 语句中设置条件? C#
How to set the condition in my if statement, if the user has to type in a whole number? C#
//Hold the Roses' cost
decimal numberofRoses;//user's desired number of roses
decimal totalCostofRoses; //the total amount of the roses' price
const decimal COST_PER_ROSE = 10;//each rose cost 10 dollars
//Get the user's input
numberofRoses = decimal.Parse(rosesTextBox.Text);
if ()//Require a condition where the user has to type in a whole number
{
}
else
{
MessageBox.Show("Please input a whole number for the number of roses");
}
除以1余数为0为整数:
if ((numberofRoses % 1) == 0)
{
}
您还可以使用 Int32.TryParse() 将数字解析为 int
,这样会更有效:
int roses = 0;
if (int.TryParse(numberofRoses, out roses)
{
//"roses" is now an int (Whole number)
}
您可以使用 TryParse()
:
int num; // use a int not a decimal. You dont want half of a rose.
if (Int32.TryParse(rosesTextBox.Text, out num)
{
// do something with num. it is an int.
}
else
{
MessageBox.Show("Please input a whole number for the number of roses");
}
//Hold the Roses' cost
decimal numberofRoses;//user's desired number of roses
decimal totalCostofRoses; //the total amount of the roses' price
const decimal COST_PER_ROSE = 10;//each rose cost 10 dollars
//Get the user's input
numberofRoses = decimal.Parse(rosesTextBox.Text);
if ()//Require a condition where the user has to type in a whole number
{
}
else
{
MessageBox.Show("Please input a whole number for the number of roses");
}
除以1余数为0为整数:
if ((numberofRoses % 1) == 0)
{
}
您还可以使用 Int32.TryParse() 将数字解析为 int
,这样会更有效:
int roses = 0;
if (int.TryParse(numberofRoses, out roses)
{
//"roses" is now an int (Whole number)
}
您可以使用 TryParse()
:
int num; // use a int not a decimal. You dont want half of a rose.
if (Int32.TryParse(rosesTextBox.Text, out num)
{
// do something with num. it is an int.
}
else
{
MessageBox.Show("Please input a whole number for the number of roses");
}