C++ Why is my function printing TWICE?

In summary: File.close();}void printUtilityStat(string, double[], int){ cout<<"Utility: "<<getSumArray("electricity","water","gas","sum","low","high","mean")<<endl; cout<<"Monthly total: "<<getSumArray("electricity","water","gas","sum","low","high","mean")<<endl;
  • #1
Joe_K
33
0

Homework Statement



My printArray function, when called in my int main() with the arguments ("***monthly total***, sums, NUM_MON) is printing out twice as many times as it should be, and for some reason, even the string caption is printing out as "******monthly total******" instead of "***monthly total***" (6 *'s instead of 3). Can anyone see any obvious mistake that I might me missing, causing this to print out wrong?

Homework Equations


The Attempt at a Solution



Code:
#include <iostream>
#include <iomanip>
#include <math.h>
#include <fstream>

//#includes

const int NUM_MON = 12;   // define number of months as constant

using namespace std;//function prototypes

void buildArrays(double[], double[], double[]);

void printUtilityStat(string, double[], int);

void getSumArray(double[], double[], double[], double[]);

void printArray(string, double[], int);

double mean(double[], int);

double sum(double[], int);

double low(double[], int);

double high(double[], int);

void sortArray(double[], int);//define arrays
double gas[NUM_MON];
double water[NUM_MON];
double electricity[NUM_MON];
double sums[NUM_MON];

int main()
{
    
    buildArrays(gas,electricity, water); //fill the three arrays
    
    
    printUtilityStat("gas", gas, NUM_MON);
    printUtilityStat("electricity", electricity, NUM_MON);
    printUtilityStat("water", water, NUM_MON); // print the stats for each utility
    

    getSumArray(gas, electricity, water, sums); //build the array of the sum of each months expenses
    
    printArray ("***monthly total***", sums, NUM_MON);
    
    sortArray (sums, NUM_MON);// sort the array using the sortArray function
    
    cout<<endl;
    
    printArray ("***sorted monthly total***", sums, NUM_MON);// print the results of the sorted array
    
    

    cout<<endl<<endl<<endl
        <<"The highest monthly expense is "<<sums[11]   <<endl<<endl   // in the sorted array, the highest expense is in the last slot
        <<"The lowest monthly expense is "<<sums[0]    <<endl<<endl    // in the sorted array, the lowest expense is in the first slot
        <<"The average monthly expense is "<<mean(sums, NUM_MON)   <<endl;// call the mean function to find the average of the sums array
        
    
    
    
    //call all worked functions with proper arguments, into the boss main function
    
system ("pause");
return 0;    
}
/*****************
This function takes 3 arrays as arguments.  Calling it will read the expenses.txt file and fill the arrays with the proper
data using for loops and temporary string variables. It returns nothing. ******************/
void buildArrays(double gas[], double electricity[], double water[])
{
     ifstream inFile;    //input file stream for data for .txt file
     
     inFile.open("expenses.txt");
     
     if (inFile.fail() )
        {
        cout<<"Unable to open expenses.txt file\n";
        exit(1);
        
        //display error message if file fails to open
        }
        
        string temp;  //define temporary variable for the words in the file, they are not needed
        int i;
        
        inFile>> temp;  // store the word in the file into this variable
        
        for (i=0; i<NUM_MON; i++)
            {
                inFile>> gas[i];  
                  }
                  
        inFile>> temp;
        
        for (i=0; i<NUM_MON; i++)
            {
                inFile>> electricity[i];  // for loop to store file content into proper array 
                  }
                  
        inFile>> temp;
        
        for (i=0; i<NUM_MON; i++)
            {
                inFile>> water[i]; // for loop to store file content into proper array  
                  }
                  
          inFile.close();             
                       }
                       
   
     
/*****************
This function takes a string, double array, and integer as arguments.  the string is a label or caption.  The function uses 
the arguments to print out the data in a formatted table with 2 decimal places. 
******************/
void printUtilityStat(string caption, double array[], int size)
{
    cout<<"***"<<caption<<"***"<<endl<<setiosflags(ios::right)
        <<"sum over 12 months: "<<setprecision(2)<<fixed<<"$"<<sum(array, size)<<endl
        <<"average           : "<<"$"<< mean(array, size)<<endl
        <<"highest cost      : "<<"$"<< high(array, size)<<endl
        <<"lowest cost       : "<<"$"<< low (array, size)<<endl<<endl;
        
        //formatted data output
     
     
     }
/*****************
This function takes 4 arrays as arguments.  It sums the contents of each subscript in each array, and stores them in a new array.
It returns nothing.******************/
void getSumArray(double gas[], double electricity[], double water[], double sums[])
{
     for (int i=0; i< NUM_MON; i++)
         {
          sums[i] = (gas[i] + electricity[i] + water[i]);
          //sum the three arays for each month and store answer in new array    
              
              }
     
     }

/*****************
This function takes a string, array, and integer for arguments.  The string is a caption or label, and it uses the array
and input integer to go through the array and print out the contents.  

******************/
void printArray(string caption, double array[], int size)
{
      cout<<"***"<<caption<<"***"<<endl;
     
     for(int i=0; i<size; i++)
     {
      cout<<setprecision(2)
          <<fixed
          <<"$"<<array[i]<<endl;
          
          //print out result of arrays with 2 decimal places and a dollar sign, using a for loop
             }
     }

/*****************
This function takes an array and integer as argument.  It uses a variable, result, and caluclated the average
using the arguments.  It returns the average. ******************/
double mean(double array[], int size)
{
       double result;
       
       result= sum(array, size);
              
        
        return  result/ size;
        
        //calculation for average
           
           
       
       }
/*****************
This function takes an array and integer as argument, and uses a for loop to go through the array and sum the contents.
It returns the sum of the contents of the array. ******************/
double sum(double array[], int size)
{
   double sum=0;   
       
       for(int i=0; i<size; i++)
       {
        sum+= array[i];    
               }
       
       return sum;
       
       //calculation to add the contents of the array together
       }/*****************
This function takes an array and integer as argument, and uses logic to find the smallest number in the array.
It then returns this number.******************/
double low(double array[], int size)
{
     double min =array[0];
  
     for (int i=1; i<size; i++)
      {
       if (array[i]<min)
          {
          min=array[i];
          }
          
          //logic for finding smallest number in array
            
       }
       
       return min;
       }
/*****************
This function takes an array and integer as argument, and uses logic to find the largest number in the array.
It then returns this number.******************/
double high(double array[], int size)
{
       double max =array[0];
  
     for (int i=1; i<size; i++)
      {
       if (array[i]>max)
          {
          max=array[i];
          }
          //logic for finding largest number in array
          
          }
          return max;

 } 
/*****************
This function takes an array and integer as argument, and sorts it with logic.  It returns nothing.******************/
void sortArray(double array[], int size)
{
     int first;
     double temp;
     
     for(int i= 0; i<size; i++)
     {
     first=i;
     for(int j=i+1; j<size; j++)
             {
              if(array[j]<array[first])
                {
                first=j;
                                       }
                                       }   
      temp= array[first];
      array[first] = array[i];
      array[i]=temp;    
      
      cout<<setprecision(2)<<fixed
          <<"$"<<array[i]
          <<endl;
             }
     
             //sort array using selection sort array similar to the example gone over in lecture
      }
 
Physics news on Phys.org
  • #2
sortArray also prints. And printArray explicitly adds three stars to each end of whatever caption you send.

Oh yes, and read (or reread) this comment on indenting.
 
Last edited:
  • #3
just a quick explanation of indenting...

the rules are: each control flow block should be a step further in the page. this makes it much easier to see what the program does, and make sure all your statements are in the right place.

as an example, your function low();
Code:
******************/
double low(double array[], int size)
{								// function starts
     double min =array[0];
  
     for (int i=1; i<size; i++)					// for loop starts here
     {
     		if (array[i]<min)						// if block
          	{		
         		 min=array[i];						// conditional statements

          	}								// if block ends
            
      }									// for loop ends here
       
      return min;
}								// function ends
/*****************
see now that you can choose a { brace, and follow it vertically down until you find a } brace, and all the lines you pass are inside that control. I noticed several mistakes form your previous version, which you've now corrected, but proper indenting makes them obvious from the start. ie:

Code:
/* this from previous thread */
double low(double array[], int size)
{
	double min = array[0];
  
	for (int i=0; i<size; i++)
	{
         	if (array[i]<min)
       		{
             		min=array[i];
         	}

                                   /* Now obvious that a } is missing at the end of the for loop*/

         return min;
}

a particularly useful aspect of this is that the compiler won't tell you "your for loop is missing a bracket", it will think your function is missing it, as your for loop steals the function's closing brace. naturally when your told that the function is missing a closing bracket, you stick one on the end, but that means your return statement is inside the for loop. the compiler won't complain, but the funtion will return the wrong value
 
  • #4
Joe_K, we appreciate you putting your code in [ code ] tags - Thanks!

Joffan and earlofwessex - very good points about indentation. I'm hopeful that Joe_K picks up on the value of good indentation in code.
 

Related to C++ Why is my function printing TWICE?

1. Why is my function printing twice even though I only called it once?

This could be due to a few reasons. One possibility is that the function is being called twice in your code, either directly or indirectly through another function. Another possibility is that there is a bug in your code that is causing the function to execute twice. It is also possible that the function is being called from multiple threads simultaneously, resulting in it being executed twice. Check your code and debugging tools to determine the cause.

2. How can I prevent my function from printing twice?

If you are experiencing this issue, the first step would be to check for any accidental or unnecessary function calls in your code. If that does not solve the issue, consider using a debugger or print statements to track the execution of your code and identify where the function is being called twice. You can also use techniques such as mutex locks to prevent multiple threads from accessing the function simultaneously.

3. Is this a common problem in C++ programming?

Yes, this is a common issue that programmers may encounter in C++. It can happen due to various reasons, such as incorrect function calls, bugs, or threading issues. It is important to carefully review and test your code to identify and resolve the root cause of the problem.

4. Can compiler optimization cause a function to print twice?

No, compiler optimization does not cause a function to print twice. It can, however, affect the order in which functions are executed, which may contribute to the issue. If you suspect that compiler optimization is causing the problem, you can try disabling it or using different optimization settings to see if it resolves the issue.

5. Is there a way to debug this issue without modifying my code?

Yes, you can use debugging tools such as gdb or Visual Studio Debugger to track the execution of your code without modifying it. These tools allow you to set breakpoints, step through your code, and examine the values of variables and functions at different points in your program. This can help you identify where and why the function is being called twice.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
8
Views
3K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
954
  • Engineering and Comp Sci Homework Help
Replies
1
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
17
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
3
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
5
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
9
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
4
Views
2K
Back
Top