我很新鲜,以C++和我面临的下一个问题的困难:用C++,得到F(N + 1)= 3/4 * F(N)4结果
写一个程序要求用户输入一个数字:n 然后计算f(n)。
注意:
f(0)=3 and f(n+1) = 3/4 * f(n) + 4 ?
例如:
f(1)= 6.25
f(2)= 8.69
f(3)= 10.52
f(4)= 11.89
f(5)= 12.92
========================= ===========================
那么,我该如何解决这个问题呢?
感谢所有..
我试试这个代码依赖于先生paxdiablo答案:
#include<iostream>
using namespace std;
int main()
{
double x=0.0;
cout<<" enter an integer N:";
cin>> x;
double f1(double x)
{
if x==0.0
return 3;
return 3/4 * f1 (x-1) + 4;
}
return 0;
}
但程序一直没有运行!
============================================== ==
正确的解决办法是:
#include<iostream>
#include<iomanip> //To enable "setprecision" tool
using namespace std;
double f(int x){
if (x==0)
{return 3;}
return (3.0/4.0) * f(x-1) + 4.0; //we add zeros to get "double" results
}
int main()
{
int n=0;
cout<<" Please, enter an integer :";
cin>> n;
cout<<fixed<<setprecision(2)<<f(n); //"setprecision" used to get only two digits after the point
return 0;
}
非常感谢大家给了我的手,特别感谢到paxdiablo先生。
你卡在哪一点?向我们展示你到目前为止所尝试的以及你得到的错误。 – Oguk 2014-11-21 00:21:44
获得“double f1(double x)”部分。并使用圆括号得到正确的答案 – mhs 2014-11-21 01:17:15
你输出'输入一个整数',但你把它读成一个double。此外,你的函数应该把一个整数作为它的输入参数(它也使比较为零安全,尽管它应该在特殊情况下用于双精度)。否则,除了一些语法错误(查阅书中的if和函数),您几乎可以解决问题。只输出结果。 – Oguk 2014-11-21 01:47:39