P5705 【深基2.例7】数字反转
题目描述
输入一个不小于 100100 且小于 10001000,同时包括小数点后一位的一个浮点数,例如 123.4123.4 ,要求把这个数字翻转过来,变成 4.3214.321 并输出。
解题思路:使用字符串比较简单
#include<iostream>
#include<cmath>
#include <string.h>
using namespace std;
int main()
{
string str;
cin>>str;
int a=str.size();//获取字符串长度
for(int i=a;i>=0;i--)//字符串反转
{
cout<<str[i];
}
return 0;
}
注意点:
如果输入字符串为123.4,此时字符串长度(a)为5。如果 int i=a,此时属于越界访问字符串的末尾。
解决方法:
将int i=a ,改成 int i=a-1 即可
P5707 【深基2.例12】上学迟到
题目描述
学校和 yyy 的家之间的距离为 ss 米,而 yyy 以 vv 米每分钟的速度匀速走向学校。
在上学的路上,yyy 还要额外花费 10 分钟的时间进行垃圾分类。
学校要求必须在上午 8:00到达,请计算在不迟到的前提下,yyy 最晚能什么时候出门。
由于路途遥远,yyy 可能不得不提前一点出发,但是提前的时间不会超过一天。
输入格式
一行两个正整数 s,vs,v,分别代表路程和速度。
输出格式
输出一个 2424 小时制下的时间,代表 yyy 最晚的出发时间。
输出格式为 HH:MMHH:MM,分别代表该时间的时和分。必须输出两位,不足前面补 00。
思路及代码
第一部分:
//定义加输入
int x,y;
cin>>x>>y;
//计算总用时(分钟)
int a=0;
if(x%y==0)
{
a=10+x/y;
}
else
{
a=11+x/y;
}
//转化为小时
int t=0;
while(a>=60)
{
a=a-60;
t++;
}
优化
//定义+输入
int x,y;
cin>>x>>y;
//计算总分钟
int a=ceil(1.0*x/y)+10;
//计算小时
int t=floor(a/60);
//计算分钟
a=a-60*t;
注意:
//计算总分钟
int a=ceil(1.0*x/y)+10;
x和y都是定义为int 类的整数,x/y表示整数相除,除法结果会执行向零舍入(即舍去小数部分),结果是一个整数,与此时我们想要的的ceil向上取整函数相悖。
解决方法:
将x/y整数相除转化成整数与浮点数混合运算,即添加1.0与x相乘,自动提升整数为浮点数,然后进行浮点除法。
第二部分
//计算输出的时间
int h,m;
//这天出发
if(a!=0&&t<=7)
{
h=7-t;
m=60-a;
}
else if(a==0&&t<=8)
{
h=8-t;
m=00;
}
//提前一天
else if(a!=0&&t>7)
{
h=7-t+24;
m=60-a;
}
else if(a==0&&t>8)
{
h=8-t+24;
m=00;
}
优化
int h,m;
//a!=0
if(a!=0)
{
h=7-t;
m=60-a;
if(h<0)
{
h=h+24;
}
}
//a==0
else if(a==0)
{
h=8-t;
m=00;
if(h<0)
{
h=h+24;
}
}
第三部分
//按格式输出
if(m<10&&h<10)
{
cout<<"0"<<h<<":0"<<m<<endl;
}
else if(m>=10&&h<10)
{
cout<<"0"<<h<<":"<<m<<endl;
}
else if(m<10&&h>=10)
{
cout<<h<<":0"<<m<<endl;
}
else if(m>=10&&h>=10)
{
cout<<h<<":"<<m<<endl;
}
完整代码
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int x,y;
cin>>x>>y;
//计算总分钟
int a=ceil(1.0*x/y)+10;
//计算小时
int t=floor(a/60);
//计算分钟
a=a-60*t;
//计算输出时分
int h,m;
if(a!=0)
{
h=7-t;
m=60-a;
if(h<0)
{
h=h+24;
}
}
else if(a==0)
{
h=8-t;
m=00;
if(h<0)
{
h=h+24;
}
}
//按格式输出
if(m<10&&h<10)
{
cout<<"0"<<h<<":0"<<m<<endl;
}
else if(m>=10&&h<10)
{
cout<<"0"<<h<<":"<<m<<endl;;
}
else if(m<10&&h>=10)
{
cout<<h<<":0"<<m<<endl;
}
else if(m>=10&&h>=10)
{
cout<<h<<":"<<m<<endl;;
}
return 0;
}
小收获
导入头文件#include<cmath>
ceil() 函数----浮点数向上取整
floor() 函数----浮点数向下取整
abs() 函数----取绝对值