c# - 无法显示所有十进制数字 C#
问题描述
我在 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 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# 代码中进行隐式转换。
推荐阅读
- excel - 在使用 TODAY() 的条件格式函数中排除标题
- java - 如何获取项目 ID
- python - 在具有精确条件的列表中添加项目
- vue.js - 对用户 Vue Devtool 隐藏 Vue 数据
- ajax - 如何处理多台服务器上的 WebSocket?
- python - Python 导入或创建包
- haskell - Haskell,如何创建有序数据 Set a = Set [a]
- javascript - D3 节点浮出框架
- visual-studio-code - 我们如何设置 DEPOT_TOOLS_WIN_TOOLCHAIN=0?
- linux - 查找文本文件中每对句子之间的相似度