Why is this code giving unexpected results?

127 Views Asked by At

When I try to run this piece of code-

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

long long fact(long long k)
{   return k/5 + k/25;
}
int main()
{
     long long n,k;
    scanf("%lld %lld", &n,&k);
    while(n--)
    {
        scanf("%lld",&k);
    printf("%d\n",fact(k));
}
}

with stdinput-

4
1
8
26
52

the output I get is-

1
6
12
12

instead of 0 1 6 12 .

Can someone explain this unexpected result ?

3

There are 3 best solutions below

1
On BEST ANSWER

Your code is broken in two places:

int main()
{
    long long n,k;
    scanf("%lld", &n);  // <<< only read n here, not n and k
    while (n--)
    {
        scanf("%lld", &k);
        printf("%lld\n", fact(k));  // <<< use %lld for long long
    }
}

Note that if you had compiled with warnings enabled (e.g. gcc -Wall ...) then your compiler would have pointed out the second mistake.

LIVE DEMO

0
On

You are reading an extra k, which is not required.

scanf("%lld %lld", &n,&k);

You don't need to input the above k as it is not used, but it counts as an input. If you instead have your input this way:

 4   // scanf("%lld %lld", &n,&k); --> reads n 
 1   // scanf("%lld %lld", &n,&k); --> reads k
 1   // scanf("%lld", &k); --> reads k for n=4
 8   // scanf("%lld", &k); --> reads k for n=3
 26  // scanf("%lld", &k); --> reads k for n=2 
 52  // scanf("%lld", &k); --> reads k for n=1

You would get the correct output. So remove the extra argument in scanf:

 scanf("%lld",&n);
0
On

The first value that is passed in long long fact method is 8. So your output will be 1. k first value is overwritten by second call.