c# - 使用循环的 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
解决方案
您没有在 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;
}
推荐阅读
- c# - 我想通过电子邮件返回用户详细信息页面,但 id 取值 id = 0 asp.net mvc c#
- javascript - javascript同时执行if else块
- javascript - 如何使用 java 脚本从不同的 html 文件动态加载引导模式内容?
- assembly - x86 汇编中的浮点运算
- java - 我的带有 final 关键字的 java 代码有错误
- c# - Winform TreeView 长时间使用后变白
- python-sphinx - 在 Sphinx 中,如何创建对表特定行的引用?
- laravel - 带有laravel的惯性重定向回同一页面并滚动位置
- controller - 通过 OpenFlow 打开与 RYU 控制器的 vSwitch 通信
- bash - IntelliJ:系统 bash 和 IntelliJ bash 不一样