I was trying to solve the record breaking day problem from kickstart .
I have two questions:
printf
function is not working but the cout
does the job (which means there is no problem with the logic)#include <bits/stdc++.h>
using namespace std;
long long solve(){
long long n;
cin >>n;
long long a[n];
for(long long j=0;j<n;j++)
cin>>a[j];
long long k=0,ans=0;
for(long long j=0;j<n-1;j++){
if(a[j]>k){
k=a[j];
if(a[j]>a[j+1]){
ans++;
}
}
}
if(a[n-1]>k)
ans++;
return ans;
}
int main(){
long long t;
cin >> t;
for(long long i=1;i<=t;i++){
printf("Case #%d: %d\n",i,solve());//instead of printf() this works: cout<<"Case #"<<i<<": "<<solve()<<endl;
}
return 0;
}
sample test case from kickstart:
4
8
1 2 0 7 2 0 2 0
6
4 8 15 16 23 42
9
3 1 4 1 5 9 2 6 5
6
9 9 9 9 9 9
output with printf():
Case #1: 0
Case #2: 0
Case #3: 0
Case #4: 0
expected output(output that i get with cout):
Case #1: 2
Case #2: 1
Case #3: 3
Case #4: 0
The printf
format code %d
expects an int
not a long long
.
The max value for an int
is 2,147,483,647 and is probably big enough for your usage.
The reason that cout
is working is because std::ostream::operator<<
is overloaded to understand long long
values.
You're using the wrong format specifier to printf
.
The %d
format specifier expects an int
but you're passing in a long long
. Using the wrong format specifier triggers undefined behavior .
To print a long long
, you need to use %lld
.
Using the <<
operator on cout
has overloads for various parameter types so it knows the type based on the chosen overload.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.