我的问题是如何才能让下面的代码只接受数字,只有在输入5以上的数字时才会相乘。
Console.WriteLine("Please enter the number of tickets sold for movie x or 1 to exit now!");
int adult = Convert.ToInt32(Console.ReadLine());
int total1 = 30 * adult;
if (adult >= 5 && adult <= 30)
{
Console.WriteLine("The total cost for the adults tickets is : {0}", total1);
}
else if (adult == 1)
{
Environment.Exit(0);
}
else
{
Console.WriteLine("Error for adults");
}
Console.WriteLine("Please enter the number of tickets sold for z or y to exit now!");
int child = Convert.ToInt32(Console.ReadLine());
int total2 = 20 * child;
if (child >= 5 && child <= 30)
{
Console.WriteLine("The total cost for the child tickets is : {0}", total2);
}
else if (child == 1)
{
Environment.Exit(0);
}
else
{
Console.WriteLine("Error for child");
}
int finTotal = total1 + total2;
Console.WriteLine("The cost of all the tickets together is : {0}", finTotal);
Console.ReadLine();
答案 0 :(得分:3)
在 if condition 中计算 total1 和 total2 。我不明白为什么要计算if语句之外的total1和total2。
例如:
if (child >= 5 && child<= 30)
{
int total2 = 20 * child;
Console.WriteLine("The total cost for the child tickets is : {0}", total2);
}
Edit1:要仅接受数字,请查看以下answer:
答案 1 :(得分:0)
这应该有效,我遗漏了你的其他if语句,但你可以写回来。
using System;
public class Program
{
public static void Main()
{
try
{
int totalAmount = 0;
Console.WriteLine("Insert the number of adult tickets sold (1 for exit)");
int adultTickets = Convert.ToInt32(Console.ReadLine());
if(adultTickets >= 5 && adultTickets <= 30)
{
totalAmount = adultTickets * 30;
}
Console.WriteLine("Insert the number of child tickets sold (1 for exit)");
int childTickets = Convert.ToInt32(Console.ReadLine());
if(childTickets >= 5 && childTickets <= 30)
{
totalAmount += childTickets * 20;
}
Console.WriteLine(totalAmount);
}
catch(FormatException)
{
Console.WriteLine("Value input was not an integer.");
}
}
}