C++primer 习题

 

 

Exercise 1.9:

What does the following for loop do? What is the final value of sum?

下列循环做什么?sum 的最终值是多少?

    int sum = 0;
    for (int i = -100; i <= 100; ++i)
        sum += i;

求-100到100的和 0

Exercise 1.10:

Write a program that uses a for loop to sum the numbers from 50 to 100. Now rewrite the program using a while.

用 for 循环编程,求从 50 到 100 的所有自然数的和。然后用 while 循环重写该程序。

 

Exercise 1.11:

Write a program using a while loop to print the numbers from 10 down to 0. Now rewrite the program using a for.

用 while 循环编程,输出 10 到 0 递减的自然数。然后用 for 循环重写该程序。

 

#include "iostream"


int main()
{
    int sum=0,sal;
    for (sal = 10; sal >= 0; --sal)
    {
        sum += sal;
    }
    std::cout <<"10到0的和为"
        << sum
        << std::endl;
    return 0;
}

//

#include "stdafx.h"
#include "iostream"


int main()
{
    int sum=0,sal=10;
    while(sal>=0)

{

    sum=+sal;

    --sal;

}
    std::cout <<"10到0的和为"
        << sum
        << std::endl;
    return 0;
}

 

Exercise 1.12:

Compare and contrast the loops you wrote in the previous two exercises. Are there advantages or disadvantages to using either form?

对比前面两个习题中所写的循环。两种形式各有何优缺点?

 

 * 一个需求:使用for循环和while循环都可以去实现,那么到底两者之间有什么区别?
 * 从内存角度考虑:
 * 局部变量在栈内存中存在,当for循环语句结束,那么变量会及时被gc(垃圾回收器)及时的释放掉,不浪费空间
 * 如果使用循环之后还想去访问循环语句中控制那个变量,使用while循环
 * 从应用场景角度考虑:
 * 如果一个需求明确循环的次数,那么使用for循环(开发中使用for循环的几率大于while循环)
 * 如果一个需求,不知道循环了多少次,使用while循环
 * 举例:吃葡萄!
 * 
 *
 * */
public class WhileDemo4 {
public static void main(String[] args) {
//使用for循环
for(int x = 1 ; x <=5 ; x++){
System.out.println("我爱高圆圆");
}

//访问for循环中控制的那个变量x
// System.out.println(x);

//使用while循环
int x = 1 ;
while(x<=5){
System.out.println("我爱高圆圆");
x ++ ;
}

//可以访问变量
System.out.println(x);

}
}

Exercise 1.13:

Compilers vary as to how easy it is to understand their diagnostics. Write programs that contain the common errors discussed in the box on 16. Study the messages the compiler generates so that these messages will be familiar when you encounter them while compiling more complex programs.

编译器不同,理解其诊断内容的难易程度也不同。编写一些程序,包含本小节“再谈编译”部分讨论的那些常见错误。研究编译器产生的信息,这样你在编译更复杂的程序遇到这些信息时就不会陌生。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值