设为首页 加入收藏

TOP

2.3 Variables (1)
2013-10-07 15:26:04 来源: 作者: 【 】 浏览:67
Tags:2.3 Variables

Imagine that we are given the problem of computing 2 to the power of 10. Our first attempt might be something like

  1. #include <iostream>  
  2. int main()  
  3. {  
  4. // a first, not very good, solution  
  5. std::cout << "2 raised to the power of 10: ";  
  6. std::cout << 2*2*2*2*2*2*2*2*2*2;  
  7. std::cout << std::endl;  
  8. return 0;  

This program solves the problem, although we might double- or triple-check to make sure that exactly 10 literal instances of 2 are being multiplied. Otherwise, we’re satisfied. Our program correctly generates the answer 1,024.

We’re next asked to compute 2 raised to the power of 17 and then to the power of 23. Changing our program each time is a nuisance. Worse, it proves to be remarkably error-prone. Too often, the modified program produces an answer with one too few or too many instances of 2.

An alternative to the explicit brute force power-of-2 computation is twofold:

1. Use named objects to perform and print each computation.

2. Use flow-of-control constructs to provide for the repeated execution of a sequence of program statements while a condition is true.

Here, then, is an alternative way to compute 2 raised to the power of 10:

  1. #include <iostream>  
  2. int main()  
  3. {  
  4. // local objects of type int  
  5. int value = 2;  
  6. int pow = 10;  
  7. int result = 1;  
  8. // repeat calculation of result until cnt is equal to pow  
  9. for (int cnt = 0; cnt != pow; ++cnt)  
  10. result *= value; // result = result * value;  
  11. std::cout << value  
  12. << " raised to the power of " 
  13. << pow << ": \t" 
  14. << result << std::endl;  
  15. return 0;  

value, pow, result, and cnt are variables that allow for the storage, modification, and retrieva l of values. The for loop allows for the repeated execution of our calculation until it’s been executed pow times.

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇2.3 Variables (2) 下一篇5. EXPRESSIONS (2)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·用 C 语言或者限制使 (2025-12-25 08:50:05)
·C++构造shared_ptr为 (2025-12-25 08:50:01)
·既然引用计数在做 GC (2025-12-25 08:49:59)
·Java 编程和 c 语言 (2025-12-25 08:19:48)
·. net内存管理宝典这 (2025-12-25 08:19:46)