P1957
#include<bits/stdc++.h>
using namespace std;
void cal(string s,int x,int y){
int res=0;
if(s=="a"){
res=x+y;
printf("%d+%d=%d\n",x,y,res);
}
if(s=="b"){
res=x-y;
printf("%d-%d=%d\n",x,y,res);
}
if(s=="c"){
res=x*y;
printf("%d*%d=%d\n",x,y,res);
}
string str=to_string(x)+"+"+to_string(y)+"="+to_string(res);
//to_string() 将int 转换为string类型
int len=str.size();
printf("%d\n",len);
}
int main(){
int n;
scanf("%d",&n);
string temp;
int x,y;
for(int i=1;i<=n;i++){
string s;
cin>>s;
if(s=="a"||s=="b"||s=="c"){
temp=s;//将符号存起来,以便下一次使用
cin>>x>>y;
}
else{//使用上一个的符号
x=stoi(s);//将string类型转换为int类型
scanf("%d",&y);
}
cal(temp,x,y);
}
return 0;
}
本题定义一个计算的函数然后代入数据即可
注意上一个的符号是要存起来,以便下一个使用;
P1308
#include<bits/stdc++.h>
using namespace std;
void huan(string &n){//将大写字母换成小写字母
int len=n.size();
for(int i=0;i<len;i++){
if(n[i]>='A'&&n[i]<='Z'){
n[i]+=32;
}
}
}
int main(){
string str,ss;
bool find=false;
getline(cin,ss);
getline(cin,str);
huan(ss);
huan(str);
int a=0,cnt=0,index=-1;
int l2=str.size();
while(a<l2){
if((str[a]!=' '&&str[a-1]==' '&&a>=1)||(str[a]!=' '&&a==0)){
int begin=a;
while(str[a]!=' '&&a<l2){
a++;
}
string temp=str.substr(begin,a-begin);
if(temp==ss){
cnt++;
if(find==false){
index=begin;
find=true;
}
}
}
else{
a++;
}
}
if(find){
cout<<cnt<<" "<<index;
}
else{
cout<<index;
}//两种情况
return 0;
}
不能用find ;
find只能查找第一次出现的如果是在同一个单词中就不满足题目要求