Skip to main content
 首页 » 编程设计

C# Tip 计算器,方法未调用,无错误消息

2024年02月05日7cmt

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
 
namespace TipCalculator 
{ 
 
class Program 
{ 
 
    static void Main(string[] args) 
    { 
        string answer; 
        float totalPrice; 
        Console.WriteLine("Would you like to calculate a tip?"); 
        answer = Console.ReadLine(); 
        if (answer == "yes") 
        { 
            Console.WriteLine("Please enter the total price of your meal"); 
            totalPrice = float.Parse(Console.ReadLine()); 
 
            if (totalPrice >= 20.00) 
                TipCalculator.over20(totalPrice); 
            else if (totalPrice < 20) 
                TipCalculator.under20(totalPrice); 
            else Console.WriteLine("Error. Please type in the value of the bill again"); 
 
        } 
        else if (answer == "no") 
            Console.WriteLine("Please run this again when you wish to calculate a tip."); 
        else 
            Console.WriteLine("Error. Please type in \"yes\" or \"no\""); 
 
        Console.ReadLine(); 
    } 
 
} 
public class TipCalculator 
{ 
    public static string over20(float bill) 
 
    { 
      float tip, totalBill; 
      tip = (bill * (float)1.2); 
      totalBill = (tip + bill); 
      return "Very good. The total tip to be paid is " + tip + " and this will cost " + totalBill + "in total."; 
 
    } 
 
    public static string under20(float bill) 
    { 
        float tip, totalBill; 
        tip = (bill * (float)1.1); 
        totalBill = (tip + bill); 
        return "Very good. The total tip to be paid is " + tip + " and this will cost " + totalBill + "in total."; 
 
    } 
} 
} 

当我尝试运行此代码时,未显示任何错误,但以“非常好”开头的消息不会显示在 over20 或 under20 消息中。提前致谢!

请您参考如下方法:

问题是您从方法 over20 和 under20 返回字符串,但您没有在任何地方使用它们。使用 Console.WriteLine 更新您的代码部分以打印输出:

if (totalPrice >= 20.00) 
    Console.WriteLine(TipCalculator.over20(totalPrice)); 
else if (totalPrice < 20) 
    Console.WriteLine(TipCalculator.under20(totalPrice)); 
else Console.WriteLine("Error. Please type in the value of the bill again"); 

Working example