C++ Primer5 第一章练习题答案ps肯定有错误,只为交流,望各位大神指正

EXERCISES SECTION 1.1.1

Exercise 1.1: Review the documentation foryour compiler and determine what file naming convention it uses. Compile andrun the main program from page 2.

Source files  .cpp; header files  .h

 

Exercise 1.2: Change the program to return-1. A return value of -1 is often treated as an indicator that the programfailed. Recompile and return your program to see how your system treats afailure indicator from main.

 There is nothing different. ?

 

EXERCISES SECTION 1.2

Exercise 1.3: Write a program to printHello, World on the standard output.

 

#include "stdafx.h"

#include<iostream>

 

int _tmain(int argc,_TCHAR* argv[])

{

    std::cout << "Helllo,World"<< std::endl;

    return 0;

}

Exercise1.4: Our program used the additionoperator, +, to add two numbers. Write a program that uses the multiplicationoperator, *, to print the product instead.

 

#include "stdafx.h"

#include<iostream>

 

int _tmain(int argc,_TCHAR* argv[])

{

    std::cout << "Enter twonumbers:"<< std::endl;

    int v1 = 0, v2 = 0;

    std::cin >> v1 >> v2;

    std::cout << "The product of"<< v1 <<" and " << v2

        << " is " << v1*v2 <<std::endl;

    return 0;

}

Exercise1.5: we wrote the output in onelarge statement. Rewrite the program to use a separate statement to print eachoperand.

#include "stdafx.h"

#include<iostream>

 

int _tmain(int argc,_TCHAR* argv[])

{

    std::cout << "Enter twonumbers:";

    std::cout << std::endl;

    int v1 = 0, v2 = 0;

    std::cin >> v1;

    std::cin >> v2;

    std::cout << "The product of";

    std::cout << v1;

    std::cout << " and ";

    std::cout << v2;

    std::cout << " is ";

    std::cout << v1*v2;

    std::cout<< std::endl;

    return 0;

}

 

Exercise 1.6: Explain whether the followingprogram fragment is legal.

   

    std::cout << "The sum of"<< v1;

              << " and " << v2;

              << " is " << v1 + v2 <<std::endl;

If theprogram is legal, what does it do? If the program isnot legal, why not? How would you fix it?

 

It is not legal. Because on the left-hand ofthe output operator (<<) must be an ostream object!

We can fix it like this: omit the semicolonbefore <<.

    std::cout << "The sum of"<< v1

              << " and " << v2

              << " is " << v1 + v2 <<std::endl;

Or we can also fix it in this way: insertstd::cout before << every line.

    std::cout << "The sum of"<< v1;

    std::cout << " and " << v2;

    std::cout << " is " << v1 + v2 <<std::endl;

 

EXERCISES SECTION 1.3

Exercise 1.7: Compile a program that hasincorrectly nested comments.

 

Exercise 1.8: Indicate which, if any, ofthe following output statements are legal:

   std::cout<< "/*";

    std::cout << "*/";

    std::cout <</*"*/"*/;

std::cout <</*"*/"/*"/*"*/ ;

After you have predicted what will happen,test your answers by compiling a program with each of these statements. Correctany errors you encounter.

     The third line std::cout<</*"*/"*/;isillegal.

EXERCISES SECTION 1.4.1

Exercise 1.9: Write a program that uses awhile to sum the numbers from 50 to 100.

 

int _tmain(int argc,_TCHAR* argv[])

{  

    //a program that uses a while to sumthe numbers from 50 to 100

    int sum = 0, val = 50;

    //keep executing the while as long asval is less than or equal to 100

    while (val <= 100){

        sum += val;//assigns sum + val to sum

        ++val;//add 1 to val

    }

    std::cout << " Sum of 50 to100 inclusive is " << sum << std::endl;

    return 0;

}

Exercise 1.10: In addition to the ++ operatorthat adds 1 to its operand,there is a decrement operator(--) that subtracts 1.Use the decrement operator to write a while that prints the numbers from tendown to zero.

int _tmain(int argc,_TCHAR* argv[])

{  

   

    int val = 10;

    //keep executing the while as long asval is greater than or equal to 0

    while (val >= 0){

        std::cout << val<< "";

        --val;

    }

    return 0;

}

Exercise 1.11: Write a program that promptsthe user for two integers. Print each number in the range specified by thosetwo integers.

 

int _tmain(int argc,_TCHAR* argv[])

{  

    std::cout << "Enter twonumbers:\n";

    int v1, v2;

    std::cin >> v1 >> v2;

    int lower, upper;

    //keep the larger one in theupper,the smaller in the lower

    if (v1 < v2){

        upper = v2;

        lower = v1;

    }

    else{

        upper = v1;

        lower = v2;

    }

    while (lower <= upper){

        std::cout << lower<< "";

        ++lower;

    }

    return 0;

}

EXERCISES SECTION 1.4.2

Exercise 1.12: what does the following for loopdo? What is the final value of sum?

    intsum=0;

for(inti=-100;i<=100;++i)

     sum+=i;

It summed the numbers from -100 through 100.The value of sum is 0.

Exercise 1.13:Rewrite the exercises from1.4.1(p.13) using for loops.

    Exercise1.9:

int _tmain(int argc,_TCHAR* argv[])

{  

    int sum = 0;

    for (int val = 10; val <= 100; val++){

        sum += val;

    }

    std::cout << "The sum ofnumbers from 50 through 100 is: "

        << sum<<std::endl;

    return 0;

}

Exercise1.10:

int _tmain(int argc,_TCHAR* argv[])

{  

   

    for (int val = 10; val >= 0; --val){

        std::cout << val<< "";

    }

    std::cout << std::endl;

    return 0;

}

         Exercise1.11:

int _tmain(int argc,_TCHAR* argv[])

{

    std::cout << "Enter twonumbers:\n";

    int v1, v2;

    std::cin >> v1 >> v2;

    int lower, upper;

    //keep the larger one in the upper,the smaller in the lower

    if (v1 < v2){

        upper = v2;

        lower = v1;

    }

    else{

        upper = v1;

        lower = v2;

    }

    for (int val = lower; val <= upper;++val){

        std::cout << val<< "";

    }

    std::cout << std::endl;

    return 0;

}                   

 

Exercise 1.14: Compare and contrast the loopsthat used a for with those using a while. Are there advantages or disadvantagesto using either form?

 

Exercise 1.15: Write programs that containthe common errors discussed in the box on page 16. Familiarize yourself withthe messages the compiler generates.

 

int _tmain(int argc,_TCHAR* argv[]

{

    return 0;

}

Error         1       error C2143: syntax error : missing ')'before '{'     

 

EXERCISES SECTION 1.4.3

Exercise 1.16: Write your own version of aprogram that prints the sum of a set of integers read from cin.

int _tmain(int argc,_TCHAR* argv[])

{

    int sum = 0, val = 0;

    while (std::cin >> val){

        sum += val;

    }

    std::cout << "Sum is " << sum <<std::endl;

    return 0;

}

EXERCISES SECTION 1.4.4

Exercise 1.17: What happens in the programpresented in this section if the input values are equal? What if there are noduplicated values?

 

There is only one output.

Every number has one output.

 

Exercise 1.18: Compile and run the programfrom this section giving it only equal values as input. Run it again giving itvalues in which no number is repeated.

 

Exercise 1.19: Revise the program you wrotefor the exercises in 1.4.1(p.13) that printed a range of numbers so that ithandles input in which the first number is smaller than the second.

 

EXERCISES SECTION 1.5.1

Exercise 1.20: http://www.informit.com/title/0321714113contains a copy of Sales_item.h in the Chapter 1 code directory. Copy that fileto your working directory. Use it to write a program that reads a set of booksales transactions, writing each transaction to the standard output.

 

#include "stdafx.h"

#include<iostream>

#include"Sales_item.h"

int _tmain(int argc,_TCHAR* argv[])

{

    Sales_item a;

    while (std::cin >> a){

        std::cout << a <<std::endl;

    }

    return 0;

}

Exercise 1.21: Write a program that readstwo Sales_item objects that have the same ISBN and produces their sum.

#include "stdafx.h"

#include<iostream>

#include"Sales_item.h"

int _tmain(int argc,_TCHAR* argv[])

{

    Sales_item a, b;

    std::cin >> a >> b;

    std::cout << a + b <<std::endl;

    return 0;

}

Exercise 1.22: Write a program that readsseveral transactions for the same ISBN. Write the sum of all the transactionsthat were read.

#include "stdafx.h"

#include<iostream>

#include"Sales_item.h"

int _tmain(int argc,_TCHAR* argv[])

{

    Sales_item trans, total;

    std::cin >> total;

    while (std::cin >> trans){

        total += trans;

    }

    std::cout << total <<std::endl;

    return 0;

}

 

EXERCISES SECTION 1.5.2

Exercise 1.23: Write a program that readsseveral transactions and counts how many transactions occur for each ISBN.

#include "stdafx.h"

#include<iostream>

#include"Sales_item.h"

int _tmain(int argc,_TCHAR* argv[])

{

    Sales_item trans, total;

    if (std::cin >> total){

        int cnt = 1;

        while (std::cin >> trans){

            if (total.isbn() == trans.isbn()){

                ++cnt;

            }

            else{//output the result,and process thenext one

                std::cout << total.isbn()<< ":\t" << cnt <<std::endl;

                total = trans;

                cnt = 1;

            }   //else     

        }//while

        std::cout <<total.isbn() << ":\t" << cnt << std::endl;

    }//outerif

    else{

        std::cerr << "Nodata?!"<< std::endl;

        return -1;

    }

    return 0;

}

 

Exercise 1.24: Test the previous program bygiving multiple transactions representing multiple ISBNs. The records for eachISBN should be grouped together.

 

EXERCISES SECTION 1.6

Exercise 1.25: Using the Sales_item.hheader from the Web site, compile and execute the bookstore program presentedin this section.

#include "stdafx.h"

#include<iostream>

#include"Sales_item.h"

int _tmain(int argc,_TCHAR* argv[])

{

        Sales_item total;// variable to hold data for the nexttransaction

 

        // read the first transaction andensure that there are data to process

        if (std::cin >> total) {

            Sales_item trans;// variable to hold the running sum

            // read and process the remainingtransactions

            while (std::cin >> trans) {

                // if we're still processingthe same book

                if (total.isbn() == trans.isbn())

                    total += trans; // update the running total

                else {

                    // print results for theprevious book

                    std::cout<< total << std::endl;

                    total =trans;  // total now refers to the next book

                }

            }

            std::cout << total<< std::endl; // print the last transaction

        }

        else {

            // no input! warn the user

            std::cerr << "Nodata?!"<< std::endl;

            return -1; //indicate failure

        }

    return 0;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值