编译器visual studio 2022,语言c++,win10系统。
一、当需用用到大小不确定的数组时,应该怎么处理?
一是用容器vector、列表list等;
二是宏定义一个数n,以该大小创建数组,当大小不合适的时候,只需要修改宏定义的值;
三是动态数组,通过new动态分配空间,并利用指针指向数组。第三种方法的数组使用与一般数组都可以通过[]运算随机访问。例如:班级人数为n,由输入确定;成绩数组为scoreP,这时可以考虑使用动态数组,代码如下:
int score;
// dynamic score array
int* scoreP = new int[n];
二、输出格式如何控制小数点的保留?
引入库iomanip,调用函数setprecision(n)实现小数点的保留,其中n是保留的位数。默认是科学计数法,超出n位部分将进行四舍五入。如果需要小数形式,则需要添加fixed。例如:保留0位小数,代码如下:
// calculate
cout << fixed << setprecision(0) << (double)pass / n * 100;
cout << "%" << endl;
cout << fixed << setprecision(0) << (double)ecellent / n * 100;
cout << "%" << endl;
输出如下:
三、蓝桥杯原题
题目:小蓝给学生们组织了一场考试,卷面总分为 100 分,每个学生的得分都是一个 0 到 100 的整数。
如果得分至少是 60 分,则称为及格。如果得分至少为 85 分,则称为优秀。
请计算及格率和优秀率,用百分数表示,百分号前的部分四舍五入保留整数。
代码:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
// the num of test attendancy
int n = 0;
cin >> n;
// error detect
while (n < 1 || n > 10000) {
cout << "illegal input of n, input it again " << endl;
cin >> n;
}
int score;
// dynamic score array
int* scoreP = new int[n];
// input score
for (int i = 0; i < n; i++) {
cin >> scoreP[i];
// error detect
while (scoreP[i] < 0 || scoreP[i] > 100) {
cout << "illegal score input, please input again" << endl;
cin >> scoreP[i];
}
}
// stats
int pass = 0; // pass students count
int ecellent = 0; // ecellent students count
for (int i = 0; i < n; i++) {
if (scoreP[i] >= 60)
pass++;
if (scoreP[i] >= 85)
ecellent++;
}
// calculate
cout << fixed << setprecision(0) << (double)pass / n * 100;
cout << "%" << endl;
cout << fixed << setprecision(0) << (double)ecellent / n * 100;
cout << "%" << endl;
return 0;
}
四、知识拓展
动态数组:https://blog.youkuaiyun.com/manchengpiaoxue/article/details/83145476