gpt4 book ai didi

C# 在 switch 语句中没有隐式失败

转载 作者:太空狗 更新时间:2023-10-29 20:24:18 26 4
gpt4 key购买 nike

我来自 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# 中执行此程序?请帮助我。

最佳答案

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;
}
}
}
}

关于C# 在 switch 语句中没有隐式失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28646183/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com