谁能帮我用C#修复此程序?

时间:2019-12-25 11:54:59

标签: c# visual-studio

我已经在计算机上编写了一个简单的Python收银机程序。但是现在我认为最好使用C#在Visual Studio中编写它,因此我开始编写代码。

但是当我测试我的程序(如下所示)时,它适用于设定的价格和卖出价格,但是当我尝试检查我的钱包时,它输出:“钱包中的钱:$”。

我实际上是一位经验丰富的C#程序员,但我从来没有团结就做C#编程,因为我通常在GameDev中工作。我也是一位经验丰富的Python程序员,所以我可以和他们一起编写脚本。

Here is the python code

static void Main(string[] args)
{
        int total = (0);
        int pricePepsi = (0);
        int priceSprite = (0);
        string[] choice =
            { "1.Set Sprite's price",
              "2.Set Pepsi's price",
              "3.Sell Sprite",
              "4.Sell Pepsi",
              "5.See wallet" };

        Console.WriteLine("--------------------CASH REGISTER--------------------");

        while (true)
        {
            foreach (string i in choice)
            {
                Console.WriteLine(i);
            }

            Console.Write("Choose one(1/2/3/4/5):");

            int choose = Convert.ToInt32(Console.ReadLine());

            if (choose == 1)
            {
                Console.Write("Set Sprite's price to:");
                priceSprite = Convert.ToInt32(Console.ReadLine());
            }

            if (choose == 2)
            {
                Console.Write("Set Pepsi's price to:");
                pricePepsi = Convert.ToInt32(Console.ReadLine());
            }

            if (choose == 3)
            {
                Console.Write("Amount of Sprites sold:");
                int sellSprite = Convert.ToInt32(Console.ReadLine());
                total = (total+(sellSprite * priceSprite));
            }

            if (choose == 4)
            {
                Console.Write("Amount of Pepsis sold:");
                int sellPepsi = Convert.ToInt32(Console.ReadLine());
                total = (total+(sellPepsi * pricePepsi));
            }

            if (choose == 5)
            {
                Console.WriteLine("Money in wallet: ",total,"$");
            }
        }  
}

2 个答案:

答案 0 :(得分:1)

您的错误在于Console.WriteLine的选项5。

if (choose == 5)
{

    //change this
    Console.WriteLine("Money in wallet: ",total,"$");
    //to this
    //Here are two alternatives. Choose one
    Console.WriteLine("Money in wallet: {0}$", total); // Composite formatting
    Console.WriteLine($"Money in wallet: {total}$"); // String interpolation
}

答案 1 :(得分:1)

C#中,您可以使用Console.WriteLine(String, Object, Object)使用指定的格式信息,将指定对象的文本表示形式以及当前行终止符写入标准输出流:

public static void WriteLine (string format, object arg0, object arg1);

您可以使用:

string yourString = string.Format("Money in wallet: , {0}$", total);

string yourString = "Money in wallet: " + total + "$";

或者您可以使用$符号和{yourVariable},例如以下示例:

string yourString = $"Money in wallet: {total}$";

但是,C#可以用货币格式格式化total

decimal total = 1800.12m; 
string yourString = String.Format("Money in wallet: {0:C}", total); 
Console.WriteLine(yourString);

输出:

  

钱包中的金额:1.800.12美元