Output is correct but SPOJ gave me wrong answer

Viewed 132

Quick question. This is the code that I wrote to finish a problem in SPOJ. The output is correct but it gives me wrong answer. Whats wrong with my code? This is the link to the question: https://www.spoj.com/problems/SUMUP/

#include <iostream>
#include <iomanip>
using namespace std;
 
void cal(int n){
    long double a, b, c;
    a = (n*n) + n;
    b = 2.0 *(n*n + n + 1.0);
    c = a / b;
    cout<< setprecision(5) << c << '\n';
}
 
int main()
{   int n, z, t;
    scanf("%d", &t);
    const int NUMS = t;
    int bobo[NUMS];
 
    for(z = 0; z < NUMS; z++){
        scanf("%d", &bobo[n]);
        cal(bobo[n]);
    }
 
 
    return 0;
}

This is the input:

5
1
2
3
4
5

This is my output:

0.33333
0.42857
0.46154
0.47619
0.48387
2 Answers

In the lines:

for(z = 0; z < NUMS; z++){
    scanf("%d", &bobo[n]);
    cal(bobo[n]);
}

You should use z instead of n when calling scanf() and cal()

SPOJ expected output seems to require trailing zeroes, which the setprecision(5) function removes from c output if there's any. To keep the trailing zeroes you can add left << setfill('0') << setw(7) in your cout to indicate that there should be at least 7 characters presents in your output line (two characters for '0.' and 5 decimal places) and if there're fewer characters, it will fill to the left side with '0's, adding back the trailing zeroes required.

cout << left << setfill('0') << setw(7) << setprecision(5) << c << '\n';

Another more elegant solution is to use printf instead

printf("%.5Lf\n",c);
void cal(int n){
    long double a, b, c;
    a = (n*n) + n;
    b = 2.0 *(n*n + n + 1.0);
    c = a / b;
    printf("%.5Lf\n",c);
}
Related