首页 > 解决方案 > 使用循环的 C# 复利计算器(错误 CS0103)

问题描述

我想在 C# 中使用不同命名空间中的两个类创建一个复利计算器,但我一生都无法弄清楚为什么我不断收到错误。

PSA 我是初学者,我知道这段代码可能看起来很糟糕,但请善待。

这是 CompoundTest.cs


namespace CompoundTest
{
       class Program
    {
        static void Main(string[] args)
        {
            CompoundClass newprogram = new CompoundClass();

            Console.Write("\nPlease enter the initial balance for your account: ");
            double balance = Convert.ToDouble(Console.ReadLine());


            Console.Write("\nPlease enter the annual interest rate: ");
            double interestRate = Convert.ToDouble(Console.ReadLine()) / 100;


            Console.Write("\nHow many years will you acrue interest? ");
            double annualAmount = Convert.ToDouble(Console.ReadLine());


            Console.WriteLine($"Your balance after {annualAmount} years is {accountBalance:C}");


            Console.ReadLine();
        }
    }
}

这是 Compound.cs


using System;

namespace Compound
{
    public class CompoundClass
    {

        private double balance;
        public int value { get; private set; }

        public CompoundClass()
        {
            Balance = value;
        }


        public double Balance
        {
            get
            {
                return balance;
            }
            private set
            {
                if (value > 0)
                {
                    balance = value;
                }
            }
        }

        public void Rate(double interestRate)
        {
          interestRate = value / 100;

        }


        public void Years(double annualAmount)
        {

         annualAmount = value * 12;


        }


        public void addMethod(double accountBalance)
        {
            for (int i = 1; i < annualAmount + 1; i++)
            {
                accountBalance = balance * Math.Pow(1 + interestRate / annualAmount, annualAmount * i);

            }
        }
    }
}

我得到错误:

CS0103 C# The name '..' does not exist in the current context - in the public void addMethod(double accountBalance) method

标签: c#

解决方案


您没有在 CompoundClass 上存储任何数据,该方法

public void Rate(double interestRate)
{
    interestRate = value / 100;
}

只对函数作用域内的输入参数 interestrate 进行操作,之后计算结果会丢失

如果你想在 CompoundClass 的整个生命周期中重用一个变量,那么将它定义为一个成员变量,例如:

private double _interestRate

并将您的功能更改为

public void Rate()
{
    _interestRate = value / 100;
}

以及年度金额

private double _annualAmount;

public void Years()
{
  _annualAmount = value * 12;
}

和你的计算

public double addMethod(double accountBalance)
{
    for (int i = 1; i < annualAmount + 1; i++)
    {
                accountBalance = balance * Math.Pow(1 + _interestRate / _annualAmount, _annualAmount * i);
    }

    return accountBalance;
}

推荐阅读