Slightly-off output in arithmetic sum

Dec 11, 2015 at 2:05am
Everything explained in code comments.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;
int main() {
/* first number is amount of triplet input [A B N];
A is the first value of the sequence, 
B is the step size and 
N is the number of first values which should be accounted. 
calculate the sum of first members of arithmetic sequence.
Sn=n/2(a1 + an); an = a1 + (n - 1)d, */

int a, n, sum, firstnum, lastnum, d;
cin >> a;
for (int i =0; i<a; i++){
    cin>> firstnum;
    cin>>d;
    cin>> n;
    lastnum = firstnum + (n-1)*d;
    sum = (n/2)*(firstnum + lastnum);
    cout << sum<<" ";}
}


Input: 8
18 5 93
13 5 29
14 11 46
12 5 35
18 17 74
25 11 28
26 18 75
1 7 80
Output: 22816 2324 12029 3298 47249 4858 51208 22200
Expected: 23064 2407 12029 3395 47249 4858 51900 22200
note that, first, second, fourth, and seventh value were off, but the others weren't. Anyone care to explain?
Last edited on Dec 11, 2015 at 2:07am
Dec 11, 2015 at 2:13am
sum = (n/2)*(firstnum + lastnum);

Integer division truncates towards zero. 5 / 7 = 0 in integer division. You probably don't want this. I fixed this and the output was the expected output.
Dec 11, 2015 at 2:24am
double fixed it, thanks.
Topic archived. No new replies allowed.