我在 C# 中有一个小方法,目的是解决这个基本方程:
我手动给 n 和 x 值
我们假设X值为3,n值为1。如果我计算方程式,我会得到这个结果:
实际结果是0.88888888,但在程序输出中我只是得到了0。
这是我的代码:
using System;
namespace Polinomio
{
class Program
{
static void Main(string[] args)
{
int x = 3;
int n = 1;
double result = 0;
for (int i = 0; i <= n; i++) {
result += (double)(Math.Pow((x - 1) / 3, Math.Pow(2, i))) / Math.Pow(2, i);
}
Console.WriteLine(result);
}
}
}
我不知道我做错了什么或错过了什么,我会感谢任何帮助。
最佳答案
只需将变量的数据类型更改为 double。
double x = 3;
int n = 1;
double result = 0;
for (int i = 0; i <= n; i++)
{
result += (Math.Pow((x - 1) / 3, Math.Pow(2, i))) / Math.Pow(2, i);
}
Console.WriteLine(result);
这样就可以了。
看这里:Implicitly converting int to double用于 C# 代码中的隐式转换优先级。
关于c# - 无法显示所有十进制数字 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58498118/