2

I'm a first semester C++ student trying to make a program where, given 3 int values it finds the sum. However, if one of the values is the same as another of the values, it does not count towards the sum The problem comes in the if / else if part of my code.

When I run it an enter something like 1, 1, 2 it should only add 1 and two but instead outputs hundreds of lines of garbage code. I don't know what I did or what I should be doing as there aren't any errors. Entering 1, 1, 1 should and does output 1, but anything outside of that use case fails.

My code is:

#include <iostream>
#include <stdlib.h>
using namespace std;

// Declare Function:
string loneSum(int num1, int num2, int num3);

int main()
{
    //Declaring vars
    int num1;
    int num2;
    int num3;

    //Obtaining user input
    cout << "Please enter number one: ";
    cin >> num1;
    cout << "Please enter number two: ";
    cin >> num2;
    cout << "Please enter number two: ";
    cin >> num3;

    cout << loneSum(num1, num2, num3);
    // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Sends user input to function
}
string loneSum(int num1, int num2, int num3) {

    if(num1 != num2 || num3) {
        cout << num1 + num2 + num3;
    }
    else if ((num1 == num2) && (num2 != num3)) {
        cout << num2 + num3;
    }
    else if ((num2 == num3) && (num3 != num1)) {
        cout << num1 + num3;
    }
    else if (num1 == num2 && num3) {
        cout << "None";
    }
}
Duffy
  • 49
  • 7
  • `if (num1 == num2 || num1 == num3) num1 = 0; if (num2 == num3) num2 = 0; return num1 + num2 + num3;` – Eljay Mar 13 '20 at 19:50
  • 1
    An good lesson for a C++ student to learn early is to enable -- and pay attention to -- [compiler warnings](https://stackoverflow.com/questions/57842756/why-should-i-always-enable-compiler-warnings). – JaMiT Mar 13 '20 at 19:53
  • @Eljay: What is expected for `loneSum(42, 42, 42)`? – Jarod42 Mar 13 '20 at 20:38
  • @Jarod42 • I'd expect loneSum(42,42,42) to be 42. But the OP's problem description isn't clear on that point. – Eljay Mar 13 '20 at 20:42
  • You do not need to update your question with the corrected code. If you do, you can post it in an answer or perhaps at the bottom of the question (so it does not detract from the question), although that is not recommended. You can just leave the question as is. Answers should be posted as answers, not edited into the questions. – Eric Postpischil Mar 13 '20 at 21:08
  • The new code shown in the question does not appear to resolve the problem that `loneSum` fails to return a `string` to its caller. – Eric Postpischil Mar 13 '20 at 21:08
  • Note that a simpler solution to calculating the sum correctly (not to the failing-to-return problem) is `int sum = num1; if (num2 != num1) sum += num2; if (num3 != num1 && num3 != num2) sum += num3;`. – Eric Postpischil Mar 13 '20 at 21:10

4 Answers4

2

The problem complained about in the title, massive “garbage” output, is caused by the fact that loneSum is declared to return a string, but it does not contain any return statement. So it is not returning what it promised, and then the behavior is not defined by the C++ standard. What happens in practice, at least in your case, is that, when cout << loneSum(num1, num2, num3); is executed, it receives some sort of uncontrolled data back in place of a string, and it attempts to process it as a string and write it to standard output.

To correct this, put a return statement in loneSum that returns a value. Since you are still writing simple programs, instead of returning a string, let’s just return an int. Change the declaration of loneSum to:

int loneSum(int num1, int num2, int num3);

Change the definition to:

int loneSum(int num1, int num2, int num3) {

And change the use of it in main to:

    cout << "The sum is " << loneSum(num1, num2, num3) << ".\n";

Now, inside loneSum, we need to calculate the correct sum, which your code was not doing. This is actually fairly easy:

  • num1 is always included in the sum, because it is not a duplicate of any earlier number.
  • num2 is included if it is not a duplicate of num1.
  • num3 is included if it is not a duplicate of num1 and is not a duplicate of num2.

Code for this is:

    int sum = num1;
    if (num2 != num1)
        sum += num2;
    if (num3 != num1 && num3 != num2)
        sum += num3;

Finally, we include the return statement your program was missing:

    return sum;
Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
1

Fixed the problem, I rewrote the code and it works fine. Here is my solution:

int sum = num1 + num2 + num3;    // This starts by adding all three vars together
if (num1 == num2) {              // checks if num1 and num2 are equal and subtracts num2
    sum = sum - num2;            //from the total if they are.
        if (num1 == num3) {      // checks if num1 and num3 are equal and 
            sum = sum - num3;    //subtracts num3 if they are
            cout << sum;         // Outputs the new total
        } else {                 // If num1 and num3 weren't equal it outputs the
            cout << sum;         //previous sum
        }}
else if (num1 != num2) {         //If num1 doesn't equal num2
        if (num2 != num3)        // and num2 doesn't equal num3
            cout << endl << sum; // Outputs the original total
        else {                   // If num2 does equal num3
            sum = sum - num3;    // Subtracts num3
            cout << sum;         // Outputs new total
        }
}
JaMiT
  • 14,422
  • 4
  • 15
  • 31
Duffy
  • 49
  • 7
  • Next step: Can you explain *why* this solution works? Keep in mind that this site is intended to help the next person with the same question as you. What can you tell those people so that they can apply your solution to their cases? (Don't worry if it's not the best explanation, but please do try to explain.) – JaMiT Mar 13 '20 at 23:39
  • How does this look? Too busy? – Duffy Mar 14 '20 at 16:36
  • It looks OK once the comments are aligned. So much better. For next time, think about how you could explain the answer before posting the code. That tends to work better than using comments in the code. – JaMiT Mar 14 '20 at 16:44
-1

Please take a look at this line of code from your program:

 if(num1 != num2 || num3) {

You say you're new to C++, but I imagine you must have some familiarity with C, so I'd encourage you to briefly review two areas:

  1. operator precedence
  2. the result of a boolean evaluation on an int.

My guess is you'll find the error in a matter of minutes, but if you get stuck, let us know, and I'll give you some more hints.

mzimmers
  • 857
  • 7
  • 17
  • This does not answer the primary question asked, indicated by the title: The program printed a lot of “garbage” output. – Eric Postpischil Mar 13 '20 at 21:06
  • Fair point. I was trying to lead the OP to the answer without giving it to him directly. Still, your answer was much more thorough than mine. – mzimmers Mar 13 '20 at 22:12
-3

First of all Why are you making the function code so complex. The basic rule of programming is K.I.S.S(Keep it simple and straight). like declare the function as int or float. and instead of using three different values take an array. //This is the code.//Sorry am new to stackoverflow so dont know how to post it.

#include<iostream>

using namespace std;

int function(int arr[ ], int n)
{
  int sum=0;
  for(int i=0;i<n;i++)
  {
    for(int j=i;j<n;j++)
    {
      for(int k=j+1;k<n;k++)
      {
        if(arr[j]==arr[k])
        { i++;  }
        else
        { sum=sum+arr[i];
          i++;
        }
      }
    }   
   }     
   return sum;
}

int main()
{
  int arr[]={1,1,2};
  for(int i=0;i<3;i++)
  { cout<<"no "<<i+1<<"="<<arr[i]<<"\t";}//displaying numbers
  cout<<"\nAnswer="<<function(arr,3);
}
Percy2-4
  • 5
  • 1
  • 1
  • 5
  • Giving a student code without documentation or explanation does not help them learn and does not answer the question that was (implicitly) asked. A students needs to understand what was wrong with their program, why it got the result it got, what a correct solution is, and why. – Eric Postpischil Mar 13 '20 at 20:08
  • For 1, 1, 1, this code produces 0 but should produce 1. For 1, 2, 1, it produces 2 but should produce 3. – Eric Postpischil Mar 13 '20 at 20:11
  • If I change the array to have 4 elements instead of 3 and invoke `function(arr,4);`, then there can be an out-of-bounds array access (trying to add `arr[5]` to `sum`. This suggests that your code is wrong (possibly because you made your code so complex instead of following the KISS principle yourself). – JaMiT Mar 13 '20 at 21:05