我正在创建CAGR计算器,但我没有得到result.can任何人帮助我? [英] I am creating CAGR calculator but I am not getting result.can any one help me?
问题描述
CAGR公式为:((最终值/起始值)^(1 / no.of yrs))减1
但总是得到0的结果。
我尝试过:
使用System;
使用System.Collections.Generic;
使用System.ComponentModel;
使用System.Data;
使用System.Drawing;
使用System.Linq;
使用System.Text;
使用System.Threading。任务;
使用System.Windows.Forms;
名称空间CAGRcalc
{
公共部分类Form1:表格
{
int SV,FV,NoY,X,Y,Z;
双重结果;
private void button2_Click(object sender,EventArgs e)
{
SV = Convert.ToInt32(txtSV.Text);
FV = Convert.ToInt32(txtFV.Text);
NoY = Convert.ToInt32(txtNoY.Text);
X = Convert.ToInt32(FV / SV);
Y = Convert.ToInt32(1 / NoY);
Z =((X)^ Y) - (1);
结果= Convert.ToDouble(Z *(100));
txtResult.Text = Result.ToString();
}
public Form1()
{
InitializeComponent();
}
}
}
CAGR formula is : ((Final value/Start value)^(1/no.of yrs)) minus 1
but always i am getting result as 0.
What I have tried:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CAGRcalc
{
public partial class Form1 : Form
{
int SV, FV,NoY,X,Y,Z;
Double Result;
private void button2_Click(object sender, EventArgs e)
{
SV = Convert.ToInt32(txtSV.Text);
FV = Convert.ToInt32(txtFV.Text);
NoY = Convert.ToInt32(txtNoY.Text);
X = Convert.ToInt32(FV / SV);
Y = Convert.ToInt32(1 / NoY);
Z = ((X) ^ Y) - (1);
Result = Convert.ToDouble(Z * (100));
txtResult.Text = Result.ToString();
}
public Form1()
{
InitializeComponent();
}
}
}
推荐答案
第一个问题:您正在使用整数除法。结果将被截断。您需要使用浮点值(double
)而不是整数(int
)。
第二个问题:在C#中,^
不会将一个数字提升到另一个数字;这是独家或运营商:
^运算符(C#引用)| Microsoft Docs [ ^ ]
您需要使用 Math.Pow函数 [ ^ ]。
第三个问题:转换如果无法将输入解析为整数,则.ToInteger
将抛出异常。如果用户键入Boo!在你的一个文本框中,你的代码会崩溃。
使用Double.TryParse [ ^ ]尝试解析输入,如果失败则向用户报告错误。
First problem: You're using integer division. The results will be truncated. You need to use floating-point values (double
) instead of integers (int
).
Second problem: In C#,^
doesn't raise one number to the power of another; it's the "Exclusive Or" operator:
^ Operator (C# Reference) | Microsoft Docs[^]
You need to use the Math.Pow function[^] instead.
Third problem:Convert.ToInteger
will throw an exception if the input cannot be parsed as an integer. If the user types "Boo!" into one of your textboxes, your code will crash.
Use Double.TryParse[^] to attempt to parse the input, and report an error to the user if it fails.
if (!double.TryParse(txtSV.Text, out double sv))
{
... Report an error to the user ...
return;
}
if (!double.TryParse(txtFV.Text, out double fv))
{
... Report an error to the user ...
return;
}
if (!double.TryParse(txtNoY.Text, out double noY))
{
... Report an error to the user ...
return;
}
double x = fv / sv;
double y = 1D / noY;
double z = Math.Pow(x, y) - 1D;
double result = z * 100D;
txtResult.Text = result.ToString();
这篇关于我正在创建CAGR计算器,但我没有得到result.can任何人帮助我?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!