10303:安全计算两个算术表达式
题目
分别打印 3 + 2 * 5 和 (3 + 2) * 5,避免在一个表达式中对同一对象进行缺少顺序保证的读写。
解析
两个待计算的表达式只含常量,不会产生副作用。把结果分别存入两个对象,可以让计算与输出边界清晰,也不会出现 i = i++ 一类未定义行为。
解析
c
#include <stdio.h>
int main(void) {
int without_parentheses = 3 + 2 * 5;
int with_parentheses = (3 + 2) * 5;
printf("3 + 2 * 5 = %d\n", without_parentheses);
printf("(3 + 2) * 5 = %d\n", with_parentheses);
return 0;
}1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
输出:
text
3 + 2 * 5 = 13
(3 + 2) * 5 = 251
2
2