Blog Archive

Monday, October 2, 2017

C++ Primer_Ed4 习题答案


Reference:
http://www.cnblogs.com/miki-52/p/5806946.html

C++ Primer Answers


Part 1 基本语言

Part 2 容器和算法

Part 3 类和数据抽象

Part 4 面向对象编程与泛型编程

 

Part 5 高级主题

附录:操作符优先级

Part 1 基本语言

Chapter 3

Exercise 3.1: 用适当的 using声明,而不用 std::,访问标准库中名字的方法,重新编写第 2.3 节的程序,计算一给定数的给定次幂的结果。

    #include <iostream>
    using  std::cin;
    using std::cout;
    using std::endl;
    int main()
    {
        int base,exponent;
        long result=1;
        cout<<"Enter base and exponent:"<<endl;
        cin>>base>>exponent;
        if(exponent<0)
        {
            cout<<"Exponent can't be smaller than 0"<<endl;
            return -1;
        }
        else
        {
            for(int cnt=1;cnt<=exponent;++cnt)
            {
                result*=base;
            }
        }
        cout<<base<<" raised to the power of "<<exponent<<":"<<result<<endl;
        //cout << "Hello world!" << endl;
        return 0;
    }



No comments:

Post a Comment