1.11M Members

Sum all between two given numbers

 
0
 

I've tried to search for a simple formula to do this but I can't find any that works for my program.
I found this: (n^2+n)/2=sum, n being the last number in the "series", but it only works if the first number is 1(which mine is necessarly not, since you should be able to input any number).

This is what my program should look like:

Input two numbers : 10 15
Numbers between 10 och 15 : 11 12 13 14
Sum 11 to 14 = 50
Avarage = 12.5

 
0
 

Formula is:

s_n = n/2 * (a0 + an)

for example,

sum from 10 to 15 is:
s_6 = 6/2 * (10 + 15 )= 75

where we note that 10 is the first term and 15 is the sixth term

More details here

 
0
 

Thanks firstPerson but I found another formula.


Okey, so I've found a formula that works and have now tried to write a program but I get the error messages:
"uninitialized local variable 'num1' used" and "uninitialized local variable 'num2' used"

#include <iostream>
using namespace std;

float calc_sum(float n, float a, float b);
float calc_av(float n, float sum);
void output(float sum, float average, float a, float b);
void input(float& a, float& b);

int main()
{
float num1, num2, n;
n=(num2-1)-(num1+1)+1;
input(num1, num2);
float total=calc_sum(n, num1, num2);
float middle=calc_av(n, total);
output(total, medel, num1, num2);
return 0;
}
float calc_sum(float n, float a, float b)
{
	return n*((b-1)-(a+1))/2;
}
float calc_av(float sum, float n)
{
	return sum/n;
}
void output(float sum, float average, float a, float b)
{
	cout<<"Sum of the numbers between "<<a<<" and "<<b<<" = "<<sum<<endl;
	cout<<"Average = "<<average<<endl;
}
void input(float& a, float& b)
{
	cout<<"Input 2 numbers: ";
	cin>>a>>b;
}

How do I fix it?

 
0
 

Your problem is that in line 12, you try to calculate the values of num1-1 and num2-1 before you have given values to num1 and num2.

If this information is not enough to allow you to fix your problem, then you don't really understand how variables work, and you need to go back to the beginning of your C++ book and start over.

 
0
 

Stupid me, saw the problem. Switched line 12 and 13 with eachother. :P
But now I get another problem, the average value doesn't calculate correctly.

I get this:
Input 2 numbers: 4 7
Sum of the numbers between 4 and 7 = 22**
Average = 0.181818


**edited

 
0
 

Because 4 + 5 + 6 + 7 = 22

 
0
 

Yes but this still doesnt explain the weird average value.
It should be 5,5 not 0,181818.

 
0
 

Try calc_av(total,n)

 
0
 

Ah thank you, now I see what's wrong =)

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article