例题1
思路1:将数字转化为字符串,看字符串中是否含有'2','0','1','9',有则算出数的平方加和
要注意算数平方和变量不能是int型,会溢出,要用long long型
#include <iostream>
#include <string>
using namespace std;
int main()
{
int cnt = 0; //统计结果
int sum = 0; //统计和
long long sp_sum = 0; //算数平方和,用int型会溢出
for(int i = 1;i<=2019;i++){
string s = to_string(i);
for(int j=0;j<s.length();j++){
if (s[j] == '2' || s[j] == '0' || s[j] == '1' || s[j] == '9'){
cnt+=1; //这样的数有多少个
sum += i; //它们的和是多少
sp_sum += i*i;
break;
}
}
}
cout<<sp_sum;
return 0;
}
思路2:分别取出数的每一位,看是否等于2,0,1,9
#include <iostream>
#include <string>
using namespace std;
int main()
{
int cnt = 0; //统计结果
int sum = 0; //统计和
long long sp_sum = 0; //算数平方和,用int型会溢出
for(int i = 1;i<=2019;i++){
int temp = i; //一定要再设置一个变量temp,不要直接对i做修改,否则i可能被重新置零
while(temp){
if(temp % 10 == 2 || temp % 10 == 0 || temp % 10 == 1 || temp % 10 == 9){
sp_sum += i*i;
break;
}
temp /= 10;
}
}
cout<<sp_sum;
return 0;
}
例题2
一根高筋拉面,中间切一刀,可以得到2根面条。
如果先对折1次,中间切一刀,可以得到3根面条
如果连续对折2次,中间切一刀,可以得到5根面条。
那么,连续对折10次,中间切一刀,会得到多少面条呢?
思路1:手算
#include <iostream>
#include <cmath>
using namespace std;
int main(){
cout<<pow(2,10)+1;
return 0;
}
思路2:本次对折弯的个数=上次对折弯的个数+上上次对折弯的个数*2(一个弯对折变三个弯)+2(绳子两端边对折变两个弯)
#include <iostream>
using namespace std;
int main(){
int wan_pre_pre = 0;//上上次对折弯的个数
int wan_pre = 0;//存上一次对折弯的个数
int wan_now = 1;//第一次对折弯的个数
for(int i = 2;i <= 10;i++){//对折十次
wan_pre_pre = wan_pre;
wan_pre = wan_now;
wan_now = wan_pre + wan_pre_pre*2 + 2;
}
cout<<wan_now+2;
return 0;
}
例题3
#include<bits/stdc++.h>
using namespace std;
int main()
{
int number_of_examinees;//考试人数
// cout<<"请输入考试人数";
cin>>number_of_examinees;
int score[number_of_examinees];//用于存放每个考生的成绩
double sum;
// cout<<"输入每个考生的成绩";
for(int i=0;i<number_of_examinees;i++){
cin>>score[i];
}
sort(score,score+number_of_examinees);
cout<<score[number_of_examinees-1]<<endl;;
cout<<score[0]<<endl;
for(int i = 0;i<number_of_examinees;i++){
sum+=score[i];
}
printf("%.2f",round(sum/number_of_examinees*100)/100);
return 0;
}