如何用c#计算乘法

本文关键字:计算 何用 | 更新日期: 2023-09-27 18:03:27

我的问题是我如何才能得到下面的代码只接受数字,只有在输入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();

如何用c#计算乘法

计算if条件中的total1total2。我不明白你为什么要在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:为了只接受数字,请看下面的答案:

这应该可以工作,我省略了你的else 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.");
        }
   }
}