Can't get anything but $0 from a call to a method to calculate a taxAmount

前端 未结 5 497
-上瘾入骨i
-上瘾入骨i 2021-01-22 11:00

I am having trouble with this following call, specially the last component:

Console.WriteLine(\"Taxpayer # {0} SSN: {1}, Income is {2:c}, Tax is {3:c}\", i + 1,          


        
5条回答
  •  有刺的猬
    2021-01-22 11:28

    Your last decision point else taxOwed = 0; will never execute, so it's not needed. I've ran your code as shown below and everything works. The problem must be with either the parameter being passed into the method being zero, or you are not setting the values like you think you are.

    void Main()
    {
        var result = CalculateTax(40000);
        Console.WriteLine(result);
    }
    
    public int CalculateTax(int income)
    {
        var incLimit = 50000;
        var lowTaxRate = 0.10;
        var highTaxRate = 0.25;
        int taxOwed;
    
        if (income < incLimit){
            taxOwed = Convert.ToInt32(income * lowTaxRate); }
        else if(income >= incLimit) {
            taxOwed = Convert.ToInt32(income * highTaxRate);}
        return taxOwed;
    }
    

    Update

    Now that you posted your full code, your problem is that you need to change the static GetRates() method to return the rates, as Clark mentions. That static method is the only place calling rates.assignRates() and those assigned rates are only good for that specific instance of rates contained in that method and nowhere else. So change GetRates() to to return the rates instance as follows:

     public static Rates GetRates()
     {
        ...
        Rates rates = new Rates();
        ...
        return rates;
     } 
    

    Then change the main method as follows:

    static void Main(string[] args)
    {
        Taxpayer[] taxArray = new Taxpayer[5];
        // Implement a for-loop that will prompt the user to enter
        // the Social Security Number and gross income.
    
        ...
    
        Rates taxRates = Taxpayer.GetRates();
    
        // Implement a for-loop that will display each object as formatted 
        // taxpayer SSN, income and calculated tax.
        for (int i = 0; i < taxArray.Length; ++i)
        {
            Console.WriteLine(
                "Taxpayer # {0} SSN: {1}, Income is {2:c}, Tax is {3:c}",
                i + 1, 
                taxArray[i].SSN, 
                taxArray[i].grossIncome,
                taxRates.CalculateTax(50000));
    
        } 
        ...
    }
    

提交回复
热议问题