首页 > 解决方案 > 无法显示所有十进制数字 C#

问题描述

我在 C# 中有一个小方法,目的是解决这个基本方程

基本方程

我手动给出nx值

我们将假设X值为3n值为1。如果我评估方程式,我会得到以下结果:

在此处输入图像描述 我的问题是输出为 0,我也尝试解析结果,但仍然显示为 0。

实际结果是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);
        }
    }
}

我不知道我做错了什么或我错过了什么,我会感谢任何帮助。

标签: c#parsingmathdouble

解决方案


只需将变量的数据类型更改为加倍。

 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);

这会成功的。

看看这里:隐式地将 int 转换为 double 以在 C# 代码中进行隐式转换。


推荐阅读