码蹄集——向下取整(求立方根)、整理玩具、三角形斜边、完全平方数、个人所得税
MT1083 向下取整
输入正整数N,求N的立方根。向下取整后输出,输出最小列宽为3列。
格式
输入格式:输入正整数N
输出格式:输出整型
样例 1
输入:3
输出: 1
求立方根方法(pow函数、二分法)
#include<bits/stdc++.h>using namespace std;int main()
{int n;cin>>n;int ans=floor(pow(n,1.0/3));printf("%3d",ans);return 0;}
MT1089 整理玩具
宝宝在整理自己的N个玩具(N<=10),有的抽屉放2个玩具,有的放1个。统计玩具可以多少种方式整理好。 注:宝宝分不清抽屉的顺序,所以 {1 2 1},{2 1 1},{1 1 2},这样的放置方式被宝宝认为是相同的。
格式
输入格式:输入正整数N
输出格式:输出整型
样例 1
输入:4
输出:3
思路:
这个题就只需要考虑能放多少个2,当2的数量确定时,就可以确定1的数量,放置的方式也就唯
一确定了,因此只需要看玩具的数量N能被拆出几个2即可。很显然N最多可以拆分出n/2(向下取整)个2,所以结果应该是 n/2+1(+1是全放1的情况)
最简单的代码:
#include<bits/stdc++.h>using namespace std;int main()
{int n;cin>>n;cout << (n/2+1);return 0;}
自己写的:
#include<bits/stdc++.h>using namespace std;int main()
{int n;cin>>n;int tmp=n,cnt=1;while(tmp){tmp-=2;cnt++;if(tmp<2)break;}cout<<cnt<<endl;return 0;}
MT1096 三角形斜边
假定直角三角形的斜边是固定长度的,输入三角形的最大可能面积,输出斜边的长度。比如最大面积为25的直角三角形,斜边的长度是10。不考虑负数,0或者其他特殊情况。不考虑溢出或者超出数据范围的情况。
格式
输入格式:输入为整型
输出格式:输出为整型
样例 1
输入:21
输出:9
直角三角形面积最大时为等腰直角三角形,此时斜边c=sqrt(4*s)
推导:
#include<bits/stdc++.h>using namespace std;int main()
{int s;cin>>s;cout<<(int)sqrt(4*s)<<endl;return 0;}
MT1098 完全平方数
输入一个正整数n,检查它是否为完全平方数。不考虑0,负数或者其他特殊情况。
格式
输入格式:输入为整型
输出格式:输出为YES或者NO
样例 1
输入:35
输出:NO
注意!!判断完全平方数需要将tmp*tmp进行强制类型转换,转成int
#include<bits/stdc++.h>using namespace std;bool check(int a)
{double tmp=sqrt(a);return (int)tmp*tmp==a;
}
int main()
{int n;cin>>n;if(check(n))cout<<"YES";elsecout<<"NO";return 0;}
MT1099 个人所得税
格式
输入格式:输入为整型
输出格式:输出为整型
样例 1
输入:500
输出:25
这题主要考宏定义的使用
使用宏定义:
#include<bits/stdc++.h>#define fun(s,rate,b) (int)(s*rate*0.01-b)using namespace std;int main()
{int s,i=0;int list_s[]={500,2000,5000,20000,40000,60000,80000,100000};int list_r[]={5,10,15,20,25,30,35,40,45};int list_b[]={0,25,125,375,1375,3375,6375,10375,15375};cin>>s;while(i<8&&s>list_s[i])i++;cout<<fun(s,list_r[i],list_b[i]);return 0;
}
没有使用宏,使用if_else:
#include<bits/stdc++.h>using namespace std;int main()
{int s;cin>>s;if(s<=500) cout<<s*5*0.01<<endl;else if(s<=2000) cout<<s*10*0.01-25<<endl;else if(s<=5000) cout<<s*15*0.01-125<<endl;else if(s<=20000) cout<<s*20*0.01-375<<endl;else if(s<=40000) cout<<s*25*0.01-1375<<endl;else if(s<=60000) cout<<s*30*0.01-3375<<endl;else if(s<=80000) cout<<s*35*0.01-6375<<endl;else if(s<=100000) cout<<s*40*0.01-10375<<endl;else cout<<s*45*0.01-15375<<endl;return 0;
}