我一直在尝试在我的代码内的屏幕快照中循环“ 1 + 1/3 + 1/5 + ... + 1 / n”部分,但无法全部完成。
编译器将正确地计算出“ x”,这对我来说唯一的问题就是循环函数中的分数。
int main()
{
int i=1,n,x=1; //x : factorial
double f;
cout<<"Enter an odd number : "<<endl;
cin>>n;
if (n%2==0)
{
cout<<"You have to enter an odd number."<<endl;
}
else
{
while(i<=n)
{
x = x * i;
f = x*(1+(1.0/n)) ;
i+=1;
}
}
cout<<"f = "<<f<<endl;}
答案 0 :(得分:0)
这是你的答案
#include <iostream>
using namespace std;
int main()
{
int n;
double f = 1;
cout<<"Enter an odd number : "<<endl;
cin >> n;
if ( n%2 == 1)
{
double temp = n;
while ( temp > 1 ) // this one calculates factorial,
{
f *= temp;
temp--;
} // f = n!
temp = 1;
double result = 0;
while ( temp <= n ) // this one calculates (1 + 1/3 + ... + 1/n)
{
result += ( 1 / temp );
temp += 2;
} // result = (1 + 1/3 + ... + 1/n)
f = f * result; // f = n! * (1 + 1/3 + ... + 1/n)
cout<<"f = "<<f<<endl;
}
else
cout<<"You have to enter an odd number."<<endl;
return 0;
}
您需要处理相同类型的数据;)
答案 1 :(得分:0)
嘿,我已经修改了您的代码,您可以运行它并可以将结果与Calulator相匹配
#include <iostream>
#include <math.h>
using namespace std;
int odnumber(int num);
int calFactorial(int num);
int main() {
int oddNumber, i = 1;
float temp=0, temp2 = 0, f = 0.0;
do
{
cout << "Enter the Odd Number: " << endl;
cin >> oddNumber;
} while (oddNumber%2 == 0);
while (i <= oddNumber)
{
if (odnumber(i))
{
temp = (double)(1.0/i);
temp2 +=temp;
}
i++;
}
f = calFactorial(oddNumber)*temp2;
cout << "F is = " << f << endl;
return 0;
}
int odnumber(int num) {
if (num % 2 != 0)
{
return 1;
}
else
{
return 0;
}
}
int calFactorial(int num) {
int x = 1, i = 1; //x is Factorial
while (i <= num)
{
x = x * i;
i++;
}
return x;
}