[英]C# no implicit fall through in switch statement
我來自C ++背景。 我最近編寫了一個程序,提供有關特定Rs的多少音符的信息。 當它要求具體金額時需要。 沒有進一步說明以下是我的代碼:
#include <iostream>
using std::cout;
using std::cin;
int main()
{
int amount,notes,choice;
cout<<"Enter the amount: ";
cin>>amount;
cout<<"Enter the value of note from which you want to start: ";
cin>>choice;
switch(choice)
{
case 100:
notes=amount/100;
cout<<"no of 100 rupees notes = "<<notes<<'\n';
amount=amount%100;
case 50:
notes=amount/50;
cout<<"no of 50 rupees notes = "<<notes<<'\n';
amount=amount%50;
case 20:
notes=amount/20;
cout<<"no of 20 rupees notes = "<<notes<<'\n';
amount=amount%20;
case 10:
notes=amount/10;
cout<<"no of 10 rupees notes = "<<notes<<'\n';
amount=amount%10;
case 5:
notes=amount/5;
cout<<"no of 5 rupees notes = "<<notes<<'\n';
amount=amount%5;
case 2:
notes=amount/2;
cout<<"no of 2 rupees notes = "<<notes<<'\n';
amount=amount%2;
case 1:
notes=amount/1;
cout<<"no of 1 rupees notes = "<<notes<<'\n';
break;
default:
cout<<"Enter only valid values";
}
return 0;
}
現在我的問題是如何在C#中編寫這個程序? 在C#中沒有隱含的通過案例,但在這個程序中需要隱含的通過案例。 那么我在C#中使用這個程序的方法是什么? 請幫我。
其原因在於,當您忘記添加break;
時,隱含的下降是導致細微錯誤的原因break;
如果你需要通過,你可以使用轉到:
case 100:
notes=amount/100;
cout<<"no of 100 rupees notes = "<<notes<<'\n';
amount=amount%100;
goto case 50;
Dennis_E對你來說是最簡單的改變,但是你可以通過使用循環結構來避免goto和多次重復:)
例如:
using System;
namespace CurrencyNotes
{
class Program
{
static void Main(string[] args)
{
int amount;
int choice;
Console.Write("Enter the amount: ");
amount = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the value of note from which you want to start: ");
choice = Convert.ToInt32(Console.ReadLine());
CountNotes(amount, choice);
}
static void CountNotes(int amount, int choice)
{
int notes = 0;
int[] choices = { 100, 50, 20, 10, 5, 2, 1 };
// Find starting choice
int i = 0;
while (choice < choices[i])
++i;
// Output number of notes for each suitable choice
while (amount > 0)
{
notes = amount / choices[i];
if (notes > 0)
Console.WriteLine("no. of {0} rupees notes = {1}", choices[i], notes);
amount %= choices[i];
++i;
}
}
}
}
就個人而言,我傾向於采用完全不同的方法。 通過陣列而不是開關。
類似於:
using System;
namespace Test
{
class MainClass
{
public static void Main (string[] args)
{
int[] notes = new int[] { 100, 50, 20, 10, 5, 2, 1 };
int amount = 0;
amount = Convert.ToInt32 (Console.ReadLine ());
foreach (int i in notes) {
Console.WriteLine (amount / i);
amount = amount % i;
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.