Week 3 - Assignment Solution
判断合法性
sin
合法,是 C++ 标准库函数名book
合法5arry
不合法,不能用数字开头_name
合法Example2.1
不合法,因为.
是 C++ 的运算符,参考Member Accessmain
合法,main
只是 C++ 的一个特殊的函数,见下例$1
视作不合法,传统标准下,非标识符,当前标准下可以,具有兼容性问题,因此视作不合法class_cpp
合法a3
合法x*y
不合法,是表达式my name
不合法,因为有空格
可以执行的是:
#include <iostream>
int main() {
int main = -1;
std::cout << "Value of main is " << main << std::endl;
return 0;
}
求表达式的值以及运算后表达式所涉及的各变量的值
都可以上机验证。
case 1:
x + (int)y % a: float = 4.5
x: float = 2.5
y: float = 8.2
a: int = 3
case 2:
(x = z * b++, b = b * x, b++): int = 42
x: float = 7
z: float = 1.4
b: int = 43
case 3:
(ch4 = ch3 - ch2 + ch1): char = \
ch4: char = \
ch3: char = 0
ch2: char = 5
ch1: char = a
case 4:
int(y / z) + (int)y / (int)z: int = 13
case 5:
!(a > b) && c && (x *= y) && b++: bool = 0
x: float = 2.5
b: int = 5
case 6:
ch3 || (b += a * c) || c++: bool = 1
b: int = 5
c: int = 0
case 7:
z = (a << 2) / (b >> 1): float = 6
Case 2:
注意 b++ 是后++
Case 5/6
最简单的“惰性求值”:
false && (expr)
则 expr
不会被计算/执行。
对
true || (expr)
同理。
Case 7:
a << 2
为 12
b >> 1
为 2
判断下列哪些是常量,哪些是变量。
"China"
const int n=10;
int m=5;
'a'
char ch='a';
int array[5]={1,2,3,4,5};
char s[ ]="Hello";
- 常量
n
常量,10
字面值常量m
变量,5
字面值常量- 常量
ch
变量,a
字面值常量array
常量(类型为指针),array[0], ... ,array[4]
变量s
常量(类型为指针),"Hello"
字面值常量
将下列算式或叙述用C++表达式描述
3.14 / 2 + sqrt(pow(asin(x), 2) + pow(c, 2))
(x + y) / ((x - y) * pow(a, y))
(x * x + y * y < a * a) && (x * x + y * y < b * b)
(a != b) && (b != c)
(k <= 20) && (ch != '\0')
求值
a=3 b=2 x=1.8 y=7 ch1='a' ch2=' ' ch3='b'
第二题验证
代码如下:
#include <iostream>
#define CHECK(expr) \
do { \
auto result = (expr); \
std::cout << #expr ": " << typeid(result).name() << " = " << (result) \
<< std::endl; \
} while (false)
#define ENV \
int a = 3, b = 5, c = 0; \
float x = 2.5, y = 8.2, z = 1.4; \
char ch1 = 'a', ch2 = '5', ch3 = '0', ch4
void case1() {
ENV;
CHECK(x + (int)y % a);
CHECK(x); CHECK(y); CHECK(a);
}
void case2() {
ENV;
CHECK((x = z * b++, b = b * x, b++));
CHECK(x); CHECK(z); CHECK(b);
}
void case3() {
ENV;
CHECK((ch4 = ch3 - ch2 + ch1));
CHECK(ch4); CHECK(ch3); CHECK(ch2); CHECK(ch1);
}
void case4() {
ENV;
CHECK(int(y / z) + (int)y / (int)z);
}
void case5() {
ENV;
CHECK(!(a > b) && c && (x *= y) && b++);
CHECK(x); CHECK(b);
}
void case6() {
ENV;
CHECK(ch3 || (b += a * c) || c++);
CHECK(b); CHECK(c);
}
void case7() {
ENV;
CHECK(z = (a << 2) / (b >> 1));
}
int main() {
std::cout << "case 1:" << std::endl; case1();
std::cout << "case 2:" << std::endl; case2();
std::cout << "case 3:" << std::endl; case3();
std::cout << "case 4:" << std::endl; case4();
std::cout << "case 5:" << std::endl; case5();
std::cout << "case 6:" << std::endl; case6();
std::cout << "case 7:" << std::endl; case7();
return 0;
}