#include <iostream>
using namespace std;
int my_sum_less_than(int x)
{
int y, sum = 0;
while( x <= y )
{
sum = x + y;
}
}
void test_function( int input, int right_answer )
{
int answer;
cout << "Calling my_sum_less_than with input " << input << "..." << endl;
answer = my_sum_less_than( input );
if( answer == right_answer )
{
cout << "...CORRECT (answer is " << answer << ")" << endl;
}
else
{
cout << "...ERROR, answer was " << answer << ", should have been " << right_answer << endl;
}
}
int main( )
{
test_function( 6, 21 );
test_function( 0, 0 );
test_function( 11, 66 );
test_function( -100, 0 );
system("pause");
return 0;
}
I'm trying to get the function to return the sum of all the whole numbers that are positive numbers less than or equal to that number that number being the parameter that was placed in. I'm not looking for the completed version even though it help out a lot but I'm looking for a clear explanation as to what I'm missing and what I clearly left out.
If you do put a completed version (hopefully it stays the same as the one I put up just with the missing things) for some reason please point out the things that were missing and why they go their I want to come out of this learning my mistakes please and thank you - Ako
I just figured out the first problem as well. You are not keeping a 'running total' of your sum as you are adding your numbers. You will need to change the line sum = x + y;
to sum += x + y
Hope this helps!
EDIT: Sorry, that didn't really solve the problem in question. You don't need another while loop, you need to change your while loop to a FOR loop
for(int i =0; i < x; i++)
The final syntax for you function should be this:
1 2 3 4
int sum = 0;
for(int i =0; i <= x; i++)
sum += i;
Erase int y altogether that is what the iterator i is for.
Sorry if I caused you confusion. I think I understand your issue better now. Hope THIS helps ^_^