0

I am a novice coder and I am currently working on the Usaco Training problems to improve my skills. This was my code for "Greedy Gift Givers". When I submit the code, I get an error that says: Execution error: Your program (`gift1') exited with signal #8 (floating point exception [usually caused by accessing memory out of bounds]). The program ran for 0.000 CPU seconds before the signal. It used 3504 KB of memory. " I have been looking through my code and trying to fix this error for a while now. Can anyone help? Please don't get angry with me as this is my first time posting, and like I said, I'm brand new to programming.

/*
ID: ashton.1
PROG: gift1
LANG: C++
*/

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    ifstream fin ("gift1.in");
    ofstream fout ("gift1.out");

    int initial, account[10], recipients, NP;
    string names[10], giver, receiver;

    fin >> NP;

    for (int k = 0; k < NP; k++)
    {
        fin >> names[k];
        account[k] = 0;
    }

    for (int k = 0; k < NP; k++)
    {
        fin >> giver >> initial >> recipients;

        for (int y = 0; y < NP; y++)
        {
            if( names[y] == giver)
                break;
        }
        account[k] -= initial;
        account[k] += initial  % recipients;

        for (int y = 0; y < recipients; y++)
        {
            fin >> receiver;

            for (int j = 0; j < NP; j++)
            {
                if(names[j] == receiver)
                    break;
            }
            if(recipients != 0)
            {
                for(int x = 0; x < NP; x++)
                {
                    account[x] += (int)initial / recipients;
                }
            }
        }
        fout << names[k] << " " << account[k] << endl;
    }

    return 0;
}   
user2977038
  • 1
  • 1
  • 1
  • It would help to see the file you are reading. – john Nov 10 '13 at 20:33
  • I would start by making sure `NP` contains what you think it does, and that moreover its value is less than 10. – Matt Phillips Nov 10 '13 at 20:35
  • Possible explanation is that you fail to open the file. **Always** test that files open successfully, e.g. `if (!fin.is_open()) { cerr << "failed to open file\n"; exit(1); }` – john Nov 10 '13 at 20:35
  • Also, a floating point exception often indicates you tried to divide by 0, or take a modulo by 0. That would hint that `recipients` is 0 in your code above. – Joe Z Nov 10 '13 at 20:48

1 Answers1

1

When you take initial % recipients you could be dividing by zero if there are no recipients. Add a conditional statement to filter that case out; this is what gives the floating point exception.