【问题标题】:finding square root of a number in C++在 C++ 中求一个数的平方根
【发布时间】:2016-12-15 06:33:37
【问题描述】:
//find square root of a number n till d decimal points
#include<iostream>
#include<iomanip>

using namespace std;
int main(){
   int n;int d;cin>>n>>d;
   double x=n;int i=1;
   while(i<=20){
       float t=(x+n/x)/2;i++;x=t;
   }
   cout<<fixed<<setprecision(d)<<x<<endl;



   }

算法似乎是正确的,但是当我认为 setprecision 将我不想要的数字四舍五入时。 setprecision() 的任何其他替代方案都不能完善我的最终答案? 输入 10 4 给我 3.1623 但是答案是 3.1622 还输入 10 7 给我 3.1622777 它确实有一个小数点后 4 位的 2。

【问题讨论】:

  • 精度的点是确定t什么时候四舍五入:这里,3.1623比3.1622更接近3.1622777,所以把它四舍五入到3并没有错。一个很好的例子是pi,主要用作3.1416而更高的精度给出 3.1415926535...两者都一样正确,只是更精确
  • 我会先试试double t = ...;
  • @RSahu 没用
  • @Adalcar 没错,但我仍然希望答案为 3.1622,因为在线法官没有通过答案

标签: c++


【解决方案1】:

要将值截断到小数点后 d,乘以 10^d,取底,然后除以相同的数字。

double multiplier = pow(10, d);
double result = floor(t * multiplier) / multiplier;
cout << fixed << setprecision(d) << result << endl;

【讨论】:

  • 谢谢,但不是只有一个语句功能可以在不四舍五入的情况下给出我的答案吗?
  • 可能有。你必须搜索。这是我能想到的最好的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多