【问题标题】:I'm having problems looping a function我在循环函数时遇到问题
【发布时间】:2020-05-02 17:13:30
【问题描述】:

funtion

我一直在尝试循环代码中屏幕截图中的“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;}

【问题讨论】:

  • 你在做整数除法。 1/n 应该是 1.0/n
  • @MikeCAT 是的,我刚刚纠正了这一点,但我仍然希望它计算分数,例如,如果我输入数字 9,代码应该计算:f = 9! (1+ 1/3 + 1/5 + 1/7 + 1/9)

标签: c++ visual-c++ c++17


【解决方案1】:

这是你的答案

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

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

【讨论】:

  • 你也可以只用一个“虽然”很容易做到这一点,你应该看看它,让它更容易更短:)
【解决方案2】:

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

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

This is the Output: Run on my Machine

【讨论】:

    猜你喜欢
    • 2017-05-19
    • 1970-01-01
    • 2019-02-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多