c++ - 如何在 C++ 中使用数学
问题描述
当我将 na 值设为 1 时,为什么结果等于 2 而不是 3。这是我的代码
#include <stdio.h>
int main()
{
int n;
float result;
scanf("%d", &n);
result = 1 + n/(2*n+1)*3/2;
while (n != 1)
{
result = result*(n-1)/(2*(n-1)+1);
n = n-1;
}
result = result * 2;
printf("%f", result);
return 0;
}
解决方案
因为n
是int
,所以右侧的数学是整数数学,而不是浮点数。然后将结果提升为浮动存储到result
.
result = 1 + n/(2*n+1)*3/2;
result = 1 + 1/3*3/2;
result = 1 + 1;
result = float(2);
使用float
常量使其实际计算为浮点数。
result =1.0f + n/(2.0f*n+1.0f)*3.0f/2.0f;
推荐阅读
- angular - 具有名称的表单控件没有值访问器:Angular 2 mat-dialog 中带有 Reactive Froms 的“rating”
- alamofire - Xcode - 没有这样的模块 alamofire
- d3.js - 带点的 D3 条形图背景
- python - 如何迭代 2 个步骤变量以在模型中找到它们的所有可能组合?
- angular - Angular 4 - 从服务器检索数据后未加载 UI - 组件变量仅在单击窗口后更新
- python - 从 N 维 Numpy 数组中仅获取非零子数组
- php - Wordpress meta_query 在两种情况下不起作用
- neo4j - Neo4j,Cypher 以节点之间不存在的关系返回结果
- c++ - 模板c++11中的查询
- javascript - 为什么我不能将 .toString 用于 this.props?反应