繁体   English   中英

我在循环 function 时遇到问题

[英]I'm having problems looping a function

功能

我一直在尝试在我的代码内的屏幕截图中循环“1 + 1/3 + 1/5 + ... + 1/n”部分,但无法全部完成。

编译器正确计算了“x”,这是正确的阶乘,现在对我来说唯一的问题是循环 function 中的分数。

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;}

这是你的答案

#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;
}

您需要对相同类型的数据进行操作;)

嘿我已经修改了你的代码,你可以运行它并且可以将你的结果与计算器匹配

#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;
}

这是 Output:在我的机器上运行

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM