1.B2018 打印字符
题目描述
输入一个 ASCII 码,输出对应的字符。
输入格式
一个整数,即字符的 ASCII 码,保证存在对应的可见字符。
输出格式
一行,包含相应的字符。
输入输出样例
输入 #1
65输出 #1
A说明/提示
保证所有数据 <128<128 并且 >0>0。
一个常见的错误写法
#include <iostream>
using namespace std;
int main()
{char a;cin>>a;cout<<a;}
输入65会输出6
原因:cin会自动识别变量的类型,根据变量类型在缓冲区读取数据,a为char类型,只取缓冲区的第一个字节(字符串65的字符6),a存储字符6
因此cout输出6
方法1:强制类型转换
#include <iostream>
using namespace std;
int main()
{short a=0;cin>>a;cout<<(char)a;}
方法2:局部变量接收
#include <iostream>
using namespace std;
int main()
{short a=0;cin>>a;char b=a;cout<<b;}
2.整型数据类型存储空间大小
【题目描述】
分别定义int,short类型的变量各一个,并依次输出它们的存储空间大小(单位:字节)。
【输入】
(无)
【输出】
一行,两个整数,分别是两个变量的存储空间大小,用一个空格隔开。
【输入样例】
(无)【输出样例】
(无)
方法1:使用sizeof
#include <iostream>
using namespace std;
int main()
{cout <<sizeof(int)<< " " <<sizeof(short);
}
方法2:不使用sizeof
注意:INT_MAX和SHRT_MAX定义在climits头文件中
#include <iostream>
#include <climits>
using namespace std;
int main()
{int a = INT_MAX;int b = SHRT_MAX;short s_a=0;short s_b = 0;while (0 != a){a = a / 16;s_a++;}while (0 != b){b = b / 16;s_b++;}cout << s_a/2 << " " << s_b/2;
}
3.浮点数向零舍入
https://www.luogu.com.cn/problem/B2016
题目描述
输入一个双精度浮点数,将其向零舍入到整数。说明:向零舍入的含义是,正数向下舍入,负数向上舍入。
输入格式
一个双精度浮点数 x。
输出格式
一个整数,即向零舍入到整数的结果。
输入输出样例
输入 #1
2.3输出 #1
2说明/提示
。
方法1:直接用long long接收
#include <iostream>
using namespace std;
long long x;
int main()
{cin>>x;cout<<x;
}
方法2:用double接收
#include <iostream>
using namespace std;
double x;
int main()
{cin>>x;long long y=(long long)x;cout<<y;
}