Difference in outputs. Why?

Given below is a C code:
#include<stdio.h>
int main()
{int t;
scanf("%d",&t);
while(t–)
{int y,m,d;
scanf("%d:%d:%d",&y,&m,&d);
if(m==4||m==6||m==9||m==11)
printf("%d\n",(61-d)/2+1);
else if(m==2)
{if(y%400==0||(y%100!=0&&y%4==0))
printf("%d\n",(29-d)/2+1);
else
printf("%d\n",(59-d)/2+1);
}
else
printf("%d\n",(31-d)/2+1);
}
return 0;
}

And given below is a C++14 code:
#include<bits/stdc++.h>
using namespace std;
int main()
{ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int T;
cin>>T;
while(T–)
{int y,m,d;
scanf("%d:%d:%d",&y,&m,&d);
if(m==4||m==6||m==9||m==11)
cout<<(61-d)/2+1<<"\n";
else if(m==2)
{if(y%400==0||(y%100!=0&&y%4==0))
cout<<(29-d)/2+1<<"\n";
else
cout<<(59-d)/2+1<<"\n";
}
else
cout<<(31-d)/2+1<<"\n";
}
return 0;
}

Now why does the C code produce correct output and the C++ code not even though they practically follow the same logic. In fact the only difference between these two code segments is that they are written in different languages.

Please format your code - the C++ code at least is uncompilable.

In spite of that, I can at least make a guess - you are mixing C-style input (scanf) with C++ -style input (cin), but are using ios_base::sync_with_stdio(false); so they are not synchronised and conflict with one another.

Edit:

Also, what input do they give different output for?

I don’t know. I was getting wrong answer in the C++ code and Correct in the C code. Anyway, thanks. You were right.

1 Like