洛谷题解
【入门2】分支结构
P5716 【深基3.例9】月份天数
题目
输入年份和月份,输出这一年的这一月有多少天。需要考虑闰年。
题解
#include<bits/stdc++.h>
using namespace std;
int year,month; //定义年和月
int a[13]={0,31,28,31,30,31,30,31,31,30,31,30,31}; //定义月份对应天数数组
int main()
{
cin>>year>>month; //输入年和月
if((year%4==0&&year%100!=0)||year%400==0)a[2]=29; //判断闰年
cout<<a[month];
}
使用数组解答年月输出问题,简化代码
P1909 买铅笔
C++中不同类型的数值表示范围(略)
TYPE | SIZE | RANDOM |
---|---|---|
bool | 1 byte | 0 / 1 |
P1055 ISBN号码
题解
#include <stdio.h>//来源于洛谷优秀题解
int main(void){
char a[15], mod[12] = "0123456789X"; //先将mod11后的十一个字符存入数组
gets(a); //输入字符串
int i, j = 1, t = 0;
for(i = 0; i < 12; i++) {
if(a[i] == '-') continue; //字符串为分隔符‘-’时跳过此次循环进入下一次循环
t += (a[i]-'0')*j++; //t储存 第j个 数字 * j 的和
}
if(mod[t%11] == a[12]) printf("Right");
else {
a[12] = mod[t%11]; //若识别码错误,则赋正确的识别码,然后输出
puts(a);
}
return 0;
}
字符型数字为减‘0’成整数
gets(),puts()函数的使用(链接)
gets() 接受一个字符串,可以接收空格并输出,来源于string流
char m[20];
gets(m); //不能写成m=gets();
储存第j个数字乘以j 的和( t += (a[i]-‘0’)*j++)
使用continue执行跳过功能
关于数组为什么要开大的问题(未解决)
P1424 小鱼的航程(改进版)
自己的题解
#include<bits/stdc++.h> //偏向于数学
using namespace std;
int main()
{
long long int x,y,m,n;
long long int w,s;
cin>>x>>y;
w=floor((y-1+x)/7)-1,s=y+x-8-w*7;
if(s/6>0) s=5;
m=w*1250+s*250;
if(x!=6&&x!=7)
{
n=(6-x)*250;
cout<<m+n;
}
else cout<<m;
}
洛谷优秀题解
#include<cstdio>
int main()
{
int n,k,s=0;//周n开始游,过了k天,游了s公里
scanf("%d %d",&n,&k);
for(int i=1;i<=k;i++)//要游k天,所以用循环
{
if(n!=6 && n!=7) s+=250;//如果不是周末则加250
if(n==7) n=1;//如果是周7,那么赋值为1
else n++;//否则n+1
}
printf("%d",s);//输出游了多少公里
return 0;
}
用for循环首尾更替和+=代替数学乘积
P1888 三角函数
题解
#include<bits/stdc++.h> //来源于洛谷优秀题解
using namespace std;
int main()
{
int a[4]; //数组用来存储三角形三条边
for (int i=0;i<3;i++) //因为是勾股数 一共只有三个数 所以循环三次来读入三个数
{
cin>>a[i]; //把数都存在一个数组
}
sort(a,a+3); //把三个数从小到大排列 此时a[0]就是最小直角边 a[2]为斜边
cout<<a[0]/__gcd(a[0],a[2])<<'/'<<a[2]/__gcd(a[0],a[2]); //因为要约分 所以用gcd(a[0],a[2])取a[0]与a[2]的最大公约数
// a[0]/最大公约数的值与a[2]/最大公约数的比值即是约分后的结果
return 0;
}
_gcd函数求最大公约数
头文件为algorithm
通过使用最大公约数达到约分效果
cout<<a[0]/__gcd(a[0],a[2])<<'/'<<a[2]/__gcd(a[0],a[2])
P4414 [COCI2006-2007#2] ABC
自己的题解
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a[3];
char b[3];
char c[3]={'A','B','C'};
for(int i=0;i<3;i++)
cin>>a[i];
sort(a,a+3);
for(int i=0;i<3;i++)
{
cin>>b[i];
for(int j=0;j<3;j++)
{
if(b[i]==c[j]) cout<<a[j]<<" "; //利用下标输出
}
}
}
洛谷优秀题解
#include<iostream>
#include<algorithm>
using namespace std;
int a[3];
char A,B,C;
int main()
{
cin>>a[0]>>a[1]>>a[2];
cin>>A>>B>>C;
sort(a,a+3);
cout<<a[A-'A']<<" "<<a[B-'A']<<" "<<a[C-'A'];//字母是大写,减去‘A’后得到0(A),1(B),2(C)。
return 0;
}