0 c# case multiplication switch-statement
我是C#的新手,并尝试使用Switch进行乘法的以下程序.该程序完全通过Switch案例,但相乘的结果不会显示在控制台中.你能帮忙吗?
using System;
public class Program
{
public static void Main(string[] args)
{
int _pLicense = 50;
int _sLicense = 100;
int _eLicense = 150;
String lType;
int nSeats;
Console.WriteLine("\n1.Personal License\n2.Startup License\n3.Enterprise License");
Console.WriteLine("Enter the license type");
lType = Console.ReadLine();
//lType = char.Parse(Console.ReadLine());
switch(lType)
{
case "1":
Console.WriteLine("Enter the number of seats");
nSeats = int.Parse(Console.ReadLine());
//Console.WriteLine(_pLicense);
int Cost = _pLicense*nSeats;
Console.WriteLine("Personal License Cost : $", +Cost);
break;
case "2":
Console.WriteLine("Enter the number of seats");
nSeats = int.Parse(Console.ReadLine());
//Console.WriteLine(_sLicense);
Cost = (_sLicense * nSeats);
Console.WriteLine("Startup License Cost : $", Cost);
break;
case "3":
Console.WriteLine("Enter the number of seats");
nSeats = int.Parse(Console.ReadLine());
//Console.WriteLine(_pLicense);
Cost = (_eLicense * nSeats);
Console.WriteLine("Enterprise License Cost : $", Cost);
break;
default:
Console.WriteLine("Invalid Type");
break;
}
}
Run Code Online (Sandbox Code Playgroud)
}
改变你Console.Writeline的
Console.WriteLine($"Personal License Cost : ${Cost}");
Run Code Online (Sandbox Code Playgroud)
和
Console.WriteLine($"Enterprise License Cost : ${Cost}");
Run Code Online (Sandbox Code Playgroud)
您也可以使用格式化成本{Cost:d}看https://docs.microsoft.com/en-us/dotnet/standard/base-types/composite-formatting.
建议您不要使用int.Parse,因为如果输入字符,它将引发错误.所以将代码改为类似的东西
if(int.TryParse(Console.ReadLine(), out int nSeats)
{
Console.WriteLine($"Enterprise License Cost : ${Cost}");
}
else
{
//Try again
}
Run Code Online (Sandbox Code Playgroud)
您不必在顶部声明nSeats,它会处理错误.
这就是我编写代码的方式
public static void Main(string[] args)
{
int nSeats = 0;
Console.WriteLine("\n1.Personal License\n2.Startup License\n3.Enterprise License");
Console.WriteLine("Enter the license type");
var lType = Console.ReadLine(); //ReadLine returns a string, so it will automatically make lType a string
int _LicenseCost = lType == "1" ? 50 : lType == "2" ? 100 : lType == "3" ? 150 : 0;
if(_LicenseCost > 0)
{
while(true)
{
Console.WriteLine("Enter the number of seats");
if(int.TryParse(Console.ReadLine(), out nSeats))
break;
else
Console.WriteLine("Please enter a valid number");
}
Console.WriteLine((lType == "1" ? "Personal" : lType == "2" ? "Startup" : lType == "3" ? "Enterprise" : "") + $" License Cost : ${_LicenseCost * nSeats}");
}
else
Console.WriteLine("License type is not valid. Good bye!");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
178 次 |
| 最近记录: |