0

Im trying to get this program working as it requires to calculate continued fraction inputed in a linked list. the programme doesn't show any error however it always crashes in the middle. Can someone help me?

The task is simply to store the programme on a linked list and then calculate it by taking the parameter from the link. It is a continued fraction.

#include <iostream>
#include <cmath>
using namespace std;
struct node
{
    int data;
    node *next;
} *h=nullptr, *t=nullptr;

float calculation (int co)
{
    float a,c;
    node *b,*f;
    b->next = f;

    while(co != 0)
    {
        f = t;
        a = (float)f->data;
        a = 1/a;
        c = (float)b->data;
        a = c + a;
        t = b;
        co--;

    }

    return a;
}

void storedata (int& c)
{
    node *n = new node;
    n->data = c;
    n->next = nullptr;
    cout<<n->data<<endl;
    if(h==nullptr)
    {
        h=n;
        t=n;
        n=nullptr;
    }
    else
    {
        t->next=n;
        t=n;
    }

}
void formula (int a, int b, int co)
{
    int c;
    int z;
    while (co!=0)
    {
        c = a/b;
        storedata(c);
        z = b*c;
        z = a-z;
        a = b;
        b = z;
        co--;
    }
}

int main ()
{
    int a,b,c,z,co,d;
    float e;

    a = 123;
    b = 100;
    co = 5;
    formula (a,b,co);
    e = calculation(co);
    cout<<"cf1 = 123/100 ="<<e;
}
Rudy Velthuis
  • 28,387
  • 5
  • 46
  • 94
  • Nobody wants to read code with one-letter variable names. Least of all your instructor. – stark Nov 15 '18 at 14:26
  • I don't know if it can help, but in a recent question I posted a code that calculates continued fraction: https://stackoverflow.com/questions/53267626/fractions-instead-of-decimals/53270382?s=15|0.0000#53270382. I don't feel at ease with ads. I will suppress this comment if people disagree. – Damien Nov 15 '18 at 16:13

1 Answers1

1

At least the following problems (some of which would be caught with warnings enabled, e.g. -Wall):

  1. Using uninitialized pointers, e.g. node *b,*f; b->next = f;. This causes undefined behavior.

  2. new but no delete anywhere, therefore memory leaks will be present.

  • What is the connection between formula and calculation. Dynamic memory variables not connected between each other. You can`t get access from one memory block to other if variables are temporary. If after working of function you exit from function all variables are destroyed and dynamic will be memory leaks. You need to connect them. – Timur Kukharskiy Nov 15 '18 at 13:30
  • @TimurKukharskiy They are actually connected. It is kind of difficult to spot, but `formula` modifies the global `t` through `storedata` and `calculation` accesses `t` as well. I agree though, that this is bad design. `h` and `t` should be local and passed around as function arguments. The naming is also bad, they should probably be `head` and `tail`. –  Nov 15 '18 at 13:33