У меня проблемы с зацикливанием функции - PullRequest
0 голосов
/ 02 мая 2020

funtion

Я тоже пытался l oop часть "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;}

Ответы [ 2 ]

0 голосов
/ 02 мая 2020

Эй, я изменил ваш код, вы можете запустить его и сопоставить ваш результат с 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;
}

Это вывод: Выполнить на моей машине

0 голосов
/ 02 мая 2020

Вот ваш ответ

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

Вам необходимо оперировать одними и теми же типами данных;)

...