如何用C++实现A+B问题?
方法1:
最简单的直接输入整数A与B,用变量C储存其和并输出。
#include <bits/stdc++.h>
using namespace std;
int main(){
int a=0,b=0;
cin>>a>>b;
int c=a+b;
cout<<c;
return 0;
}
洛谷提交完,不用O2优化耗时34ms。
方法2:
有没有更快的方法?cin和cout处理比scanf、printf慢。
#include <bits/stdc++.h>
using namespace std;
int main(){
int a=0,b=0;
scanf("%d%d",&a,&b);
int c=a+b;
printf("%d",c);
return 0;
}
洛谷提交完,不用O2优化耗时33ms,快了1ms。
方法3:
getchar、putchar比scanf、printf都要快,那就用它们来一位一位输出。
#include <bits/stdc++.h>
using namespace std;
inline int read(){
int x=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9'){
if(ch=='-')f=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9'){
x=x*10+ch-'0';
ch=getchar();
}
return x*f;
}
void write(int x){
if(x<0)x=-x,putchar('-');
if(x>9)write(x/10);
putchar(x%10+'0');
}
int main(){
write(read()+read());
return 0;
}
洛谷提交完,不用O2优化耗时30ms,又快了3ms。
这里涉及到了快读快写,当然还有更快的方法,本人就只会这些了。
欢迎来洛谷联系我。