牛客cpp:牛客网在线编程
2024年4月10日:BC1—>BC8
BC4:浮点数精度保留
问题:不加入fixed输入0.359813,最后得到0.36,并不是强制保留0.360。这种写法会保留小数点后三位精度,但是最后输出会省略掉最后的0不打印。
#include <ios>
#include <iostream>
#include <iomanip>
using namespace std;int main() {float a;cin >> a;cout << fixed <<setprecision(3);cout << a << endl;
}
解决:在设置精度前加入sdt::fixed固定精度。
std::fixed 用于指定浮点数的定点表示法,而 std::setprecision(3) 则设置小数位数为三位。
BC8:字符菱形(for嵌套循环)
之前理解的for循环嵌套,外层循环打印行数,内层循环打印列数有点小瑕疵。没打印空格之前,#是不能占据第一个位置的(并不是一个矩阵!)
内层循环打印列数这句话并不是很准确。进入行之后只对这一行关注即可。
include <iostream>
using namespace std;int main()
{string str =“#”;for (int i = 0; i < 5; i++) {if(i<3) // 上半部分{for(int j=0;j<2-i;j++){cout << " ";}for(int k=0;k<2*i+1;k++){cout << str;}cout << endl;}else //下半部分{for(int j=0;j<i-2;j++){cout << " ";}for(int k=0;k<9-2*i;k++){cout << str;}cout <<endl;}}
}
2024年4月10日:BC9—>BC
BC9:字符转ASCII码
强制类型转换
int ascii = static_cast<int>(ch);
BC10:四舍五入
输入:14,99;输出:15
double a;
int b = round(a);
BC12:加入间隔的输入和控制精度输出
问题1:输入信息中有分号和逗号的情况下cin中加入char ch来控制;
问题2:变量类型声明为double,最后控制精度输出无法做到四舍五入。是因为double类型和setprecision不匹配,换位float即可。
输入:17140216;80.845,90.55,100.00
输出:The each subject score of No. 17140216 is 80.85, 90.55, 100.00.
#include <ios>
#include <iostream>
#include <iomanip>
using namespace std;int main() {int id_number;float score1, score2, score3;char ch;cin >> id_number >> ch >> score1 >> ch >> score2 >> ch >> score3;cout << "The each subject score of No. " << id_number<< " is " << fixed << setprecision(2) << score1 << ", " << score2 << ", " <<score3 << "." << endl;
}
BC13:字符串截断
这种题目最好使用字符串,方便截断处理。使用substr函数,参数为开始位置和截取长度。
输入:20130225 输出: year=2013 month=02 date=25
#include <iostream>
using namespace std;int main() {string date;cin >> date;cout << "year=" << date.substr(0, 4) << endl;cout << "month=" << date.substr(4, 2) << endl;cout << "date=" << date.substr(6, 2) << endl;
}
BC14:C语言风格的输入输出
在一行内输入:a=1,b=2。用cin有点难度,但是c语言风格的输入就方便很多。头文件不需要改。
scanf("a=%d,b=%d", &a, &b);
BC15:大小写转换和读取键入的字符
getchar函数专门用于读取键盘键入的字符,还可以用于丢弃Enter键。
#include <iostream>
using namespace std;int main() {char ch;char a;while ((ch = getchar()) != EOF) {getchar();a=tolower(ch);cout << a << endl;}return 0;
}
BC19 对齐
使用iomanip库中的setw()函数,来固定对齐格式,setw() 设置的字段宽度只对下一个输出项起作用。
例如使用setw(8),该函数意味着控制下一个输出的字段宽度为 8 个字符,不足8个长度则前面用空格补充。
#include <iostream>
#include <iomanip>
using namespace std;int main() {int a, b, c;scanf("%d %d %d", &a, &b, &c);cout << a << setw(8) << b << setw(8) << c << endl;
}