4-x 第四章总结与测验(todo)
章节回顾
内存的最小单位是二进制位binary digit,也称为比特bit。可直接寻址(访问)的最小内存单位是字节byte。现代标准规定一个字节等于8比特。
数据类型data type告知编译器如何以特定方式解释内存内容。
C++支持多种基础数据类型,包括浮点数、整数、布尔值、字符、空指针及void类型。
void用于表示无类型,主要用于标识函数不返回值的情况。
不同类型占用内存量各异,且内存使用量可能因机器而异。
相关内容
参见 4.3 -- 对象大小与 sizeof 运算符,其中给出了每种基本类型的最小大小对照表。
sizeof 运算符可用于返回某种类型的字节大小。
有符号整数Signed integers用于存储正负整数(包括0)。特定数据类型可存储的值范围称为其取值范围range。使用整数时需警惕溢出和整数除法问题。
无符号整数Unsigned integers仅存储正数(及0),除非进行位操作,通常应避免使用。
固定宽度整数Fixed-width integers具有固定大小,但并非所有架构都支持。fastest_integer 和 smallest_integer 表示满足最小大小要求的最快/最小整数类型。应避免使用 std::int8_t 和 std::uint8_t,因其行为更接近 char 类型而非整数类型。
size_t是一种无符号整数类型,用于表示对象的大小或长度。
科学记数法Scientific notation是书写长数字的简写方式。C++支持浮点数配合科学记数法。有效数字(即e前面的部分)中的数字称为有效数字significant digits。
浮点数Floating point是一组用于存储实数(包括带小数部分的数值)的数据类型。数值的精度precision决定了其在不丢失信息的情况下能表示多少有效位。当浮点数存储的有效位过多而其精度不足时,就会产生舍入误差rounding error。舍入误差无处不在,即便是0.1这类简单数值也不例外。因此不应直接比较浮点数。
布尔类型Boolean用于存储真值或假值。
if语句If statements允许在条件为真时执行一行或多行代码。if语句的条件表达式会被解释为布尔值。else语句else statement用于在先前if语句条件评估为假时执行相应语句。
char用于存储被解释为ASCII字符的值。使用char时需注意区分ASCII码值与普通数字。将字符作为整数值打印需使用static_cast。
C++中尖括号通常表示需要可参数化类型parameterizable type的表达式。配合static_cast使用时,用于确定实参应转换为何种数据类型(例如static_cast
测验时间
问题 #1
为下列每种情况选择变量的合适数据类型。尽可能具体说明。若答案为整数,则选择 int(若大小不重要),或根据取值范围选择特定的固定宽度整数类型(如 std::int16_t)。
a) 用户年龄(以年为单位)(假设类型大小不重要)
显示答案
int
b) 用户是否希望应用程序检查更新
显示答案
bool
c) π(3.14159265)
显示答案
double
d) 教科书的页数(假设大小不重要)
显示答案
由于书籍页数通常不会超过32,767页,因此int类型在此处应该足够使用。
e) 沙发长度(单位:英尺,保留两位小数)(假设大小重要)
显示答案
float
f) 出生以来眨眼的次数(注:答案为数百万级)
显示答案
std::int32_t
g) 用户通过字母选择菜单选项
显示答案
char
h) 某人的出生年份(假设大小重要)
显示答案
std::int16_t。您可以使用正数表示公元纪年的出生日期,使用负数表示公元纪元前的出生日期。
问题 #2
作者注
从这里开始,测验难度将逐步提升。这些要求编写程序的测验旨在确保您能综合运用课程中呈现的多个概念。请做好投入时间解决这些问题的准备。若您是编程新手,不必期望能立即解答这些问题。
请记住,此处的目标是帮助你明确掌握的内容,以及需要重点复习的概念。遇到困难是正常的。
以下建议供参考:
- 不要试图一次性编写完整解决方案。先编写一个函数,测试确保其按预期运行后再继续。
- 使用调试器定位问题根源。
- 回顾本章前几节的测验答案,其中常包含相似概念。
若确实卡住,可查看解答,但务必先理解每行代码的作用再继续。只要最终掌握了概念,无论靠自己解出还是参考解答都无妨。
编写以下程序:用户需输入两个浮点数(使用double类型)。随后用户需输入以下数学运算符之一:+、-、* 或 /。程序将对用户输入的两个数进行运算并输出结果。若用户输入无效运算符,程序应不输出任何内容。
程序示例:
Enter a double value: 6.2
Enter a double value: 5
Enter +, -, *, or /: *
6.2 * 5 is 31

显示提示
提示:编写三个函数:一个用于获取双精度数值,一个用于获取运算符号,一个用于计算并输出结果。
显示提示
提示:使用if语句和运算符==将用户输入与所需的算术符号进行比较。
显示提示
提示:若用户未传递支持的操作,请考虑使用提前返回(详见第4.10节——if语句介绍)。
显示答案
#include <iostream>
double getDouble()
{
std::cout << "Enter a double value: ";
double x{};
std::cin >> x;
return x;
}
char getOperator()
{
std::cout << "Enter +, -, *, or /: ";
char operation{};
std::cin >> operation;
return operation;
}
void printResult(double x, char operation, double y)
{
double result{};
if (operation == '+')
result = x + y;
else if (operation == '-')
result = x - y;
else if (operation == '*')
result = x * y;
else if (operation == '/')
result = x / y;
else // if the user did not pass in a supported operation
return; // early return
std::cout << x << ' ' << operation << ' ' << y << " is " << result << '\n';
}
int main()
{
double x { getDouble() };
double y { getDouble() };
char operation { getOperator() };
printResult(x, operation, y);
return 0;
}
问题 #3
附加题:这道题稍具挑战性。
编写一个简短程序,模拟从塔顶抛下球的过程。程序开始时需让用户输入塔的高度(单位:米)。假设重力加速度为9.8 m/s²,且球初始静止(无初始速度)。程序需输出球在0、1、2、3、4、5秒时距地面的高度。注意:球体高度不得低于地面(高度为0)。
使用函数计算x秒后的球体高度。该函数应通过以下公式计算x秒内的下落距离:下落距离 = 重力常数 * x秒² / 2
预期输出:
Enter the height of the tower in meters: 100
At 0 seconds, the ball is at height: 100 meters
At 1 seconds, the ball is at height: 95.1 meters
At 2 seconds, the ball is at height: 80.4 meters
At 3 seconds, the ball is at height: 55.9 meters
At 4 seconds, the ball is at height: 21.6 meters
At 5 seconds, the ball is on the ground.
注意:根据塔的高度,球可能无法在5秒内落地——这没关系。等我们学完循环后会改进这个程序。
注意:在C++中^符号不是幂运算符。请使用乘法而非幂运算实现该公式。
注意:请记得使用双精度数字表示双精度类型,例如2.0而非2。
显示解决方案
#include <iostream>
// Gets tower height from user and returns it
double getTowerHeight()
{
std::cout << "Enter the height of the tower in meters: ";
double towerHeight{};
std::cin >> towerHeight;
return towerHeight;
}
// Returns the current ball height after "seconds" seconds
double calculateBallHeight(double towerHeight, int seconds)
{
double gravity { 9.8 };
// Using formula: s = (u * t) + (a * t^2) / 2
// here u (initial velocity) = 0, so (u * t) = 0
double fallDistance { gravity * (seconds * seconds) / 2.0 };
double ballHeight { towerHeight - fallDistance };
// If the ball would be under the ground, place it on the ground
if (ballHeight < 0.0)
return 0.0;
return ballHeight;
}
// Prints ball height above ground
void printBallHeight(double ballHeight, int seconds)
{
if (ballHeight > 0.0)
std::cout << "At " << seconds << " seconds, the ball is at height: " << ballHeight << " meters\n";
else
std::cout << "At " << seconds << " seconds, the ball is on the ground.\n";
}
// Calculates the current ball height and then prints it
// This is a helper function to make it easier to do this
void calculateAndPrintBallHeight(double towerHeight, int seconds)
{
double ballHeight{ calculateBallHeight(towerHeight, seconds) };
printBallHeight(ballHeight, seconds);
}
int main()
{
double towerHeight{ getTowerHeight() };
calculateAndPrintBallHeight(towerHeight, 0);
calculateAndPrintBallHeight(towerHeight, 1);
calculateAndPrintBallHeight(towerHeight, 2);
calculateAndPrintBallHeight(towerHeight, 3);
calculateAndPrintBallHeight(towerHeight, 4);
calculateAndPrintBallHeight(towerHeight, 5);
return 0;
}
对于这个程序,我们有三个任务:获取初始塔高、计算球的当前高度以及打印球的当前高度。遵循函数应专注于单一功能的最佳实践,我们为每个任务分别定义了独立函数。calculateAndPrintBallHeight() 作为辅助函数,能在主函数调用时使高度计算与打印操作更具可读性。

浙公网安备 33010602011771号