c语言程序设计第五版习题答案解析
- 格式:docx
- 大小:37.33 KB
- 文档页数:3
C++ Primer Plus 第五版编程题解.txt如果有来生,要做一棵树,站成永恒,没有悲伤的姿势。
一半在土里安详,一半在风里飞扬,一半洒落阴凉,一半沐浴阳光,非常沉默非常骄傲,从不依靠从不寻找。
Solutions for Programming Exercises in C++ Primer Plus, 5th EditionChapter 2// pe2-2.cpp#include <iostream>int main(void){using namespace std;cout << "Enter a distance in furlongs: ";double furlongs;cin >> furlongs;double feet;feet = 220 * furlongs;cout << furlongs << " furlongs = "<< feet << " feet\n";return 0;}// pe2-3.cpp#include <iostream>using namespace std;void mice();void run();int main(){mice();mice();run();run();return 0;}void mice(){cout << "Three blind mice\n";}void run(){cout << "See how they run\n";}// pe2-4.cpp#include <iostream>double C_to_F(double);int main(){using namespace std;cout << "Enter a temperature in Celsius: "; double C;cin >> C;double F;F = C_to_F(C);cout << C << " degrees Celsius = "<< F << " degrees Fahrenheit\n";return 0;}double C_to_F(double temp){return 1.8 * temp + 32.0;}Chapter 3// pe3-1.cpp#include <iostream>const int Inch_Per_Foot = 12;int main(void){using namespace std;// Note: some environments don't support the backspace charactercout << "Please enter your height in inches: ___/b/b/b ";int ht_inch;cin >> ht_inch;int ht_feet = ht_inch / Inch_Per_Foot;int rm_inch = ht_inch % Inch_Per_Foot;cout << "Your height is " << ht_feet << " feet, ";cout << rm_inch << " inch(es).\n";return 0;}// pe3-3.cpp#include <iostream>const double MINS_PER_DEG = 60.0;const double SECS_PER_MIN = 60.0;int main(){using namespace std;int degrees;int minutes;int seconds;double latitude;cout << "Enter a latitude in degrees, minutes, and seconds:\n";cout << "First, enter the degrees: ";cin >> degrees;cout << "Next, enter the minutes of arc: ";cin >> minutes;cout << "Finally, enter the seconds of arc: ";cin >> seconds;latitude = degrees + (minutes + seconds / SECS_PER_MIN)/MINS_PER_DEG; cout << degrees << " degrees, " << minutes << " minutes, "<< seconds << " seconds = " << latitude << " degrees\n";return 0;}// pe3-5.cpp#include <iostream>int main(void){using namespace std;cout << "How many miles have you driven your car? ";float miles;cin >> miles;cout << "How many gallons of gasoline did the car use? ";float gallons;cin >> gallons;cout << "Your car got " << miles / gallons;cout << " miles per gallon.\n";return 0;}// pe3-6.cpp#include <iostream>const double KM100_TO_MILES = 62.14;const double LITERS_PER_GALLON = 3.875;int main ( void ){using namespace std;double euro_rating;double us_rating;cout << "Enter fuel consumption in liters per 100 km: ";cin >> euro_rating;// divide by LITER_PER_GALLON to get gallons per 100-km// divide by KM100_TO_MILES to get gallons per mile// invert result to get miles per gallonus_rating = (LITERS_PER_GALLON * KM100_TO_MILES) / euro_rating; cout << euro_rating << " liters per 100 km is ";cout << us_rating << " miles per gallon.\n";return 0;}Chapter 4// pe4-2.cpp -- storing strings in string objects#include <iostream>#include <string>int main(){using namespace std;string name;string dessert;cout << "Enter your name:\n";getline(cin, name); // reads through newlinecout << "Enter your favorite dessert:\n";getline(cin, dessert);cout << "I have some delicious " << dessert;cout << " for you, " << name << ".\n";return 0;}// pe4-3.cpp -- storing strings in char arrays#include <iostream>#include <cstring>const int SIZE = 20;int main(){using namespace std;char firstName[SIZE];char lastName[SIZE];char fullName[2*SIZE + 1];cout << "Enter your first name: ";cin >> firstName;cout << "Enter your last name: ";cin >> lastName;strncpy(fullName,lastName,SIZE);strcat(fullName, ", ");strncat(fullName, firstName, SIZE);fullName[SIZE - 1] = '\0';cout << "Here's the information in a single string: " << fullName << endl;return 0;}// pe4-5.cpp// a candybar structurestruct CandyBar {char brand[40];double weight;int calories;};#include <iostream>int main(){using namespace std; //introduces namespace stdCandyBar snack = { "Mocha Munch", 2.3, 350 };cout << "Brand name: " << snack.brand << endl;cout << "Weight: " << snack.weight << endl;cout << "Calories: " << snack.calories << endl;return 0;}// p#include <iostream>const int Slen = 70;struct pizza {char name[Slen];float diameter;float weight;};int main(void){using namespace std;pizza pie;cout << "What is the name of the pizza company? ";cin.getline(, Slen);cout << "What is the diameter of the pizza in inches? "; cin >> pie.diameter;cout << "How much does the pizza weigh in ounces? ";cin >> pie.weight;cout << "Company: " << << "\n";cout << "Diameter: " << pie.diameter << " inches\n";cout << "Weight: " << pie.weight << " ounces\n";return 0;}Chapter 5// pe5-2.cpp#include <iostream>int main(void){using namespace std;double sum = 0.0;double in;cout << "Enter a number (0 to terminate) : ";cin >> in;while (in != 0) {sum += in;cout << "Running total = " << sum << "\n";cout << "Enter next number (0 to terminate) : ";cin >> in;}cout << "Bye!\n";return 0;}// pe5-4.cpp// book sales#include <iostream>const int MONTHS = 12;const char * months[MONTHS] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};int main(){using namespace std; //introduces namespace stdint sales[MONTHS];int month;cout << "Enter the monthly sales for \"C++ for Fools\":\n"; for (month = 0; month < MONTHS; month++){cout << "Sales for " << months[month] << ": ";cin >> sales[month];}double total = 0.0;for (month = 0; month < MONTHS; month++)total += sales[month];cout << "Total sales: " << total << endl;return 0;}// pe5-6.cpp#include <iostream>struct car { char name[20]; int year;};int main(void){using namespace std;int n;cout << "How many cars do you wish to catalog?: ";cin >> n;while(cin.get() != '\n') // get rid of rest of line;car * pc = new car [n];int i;for (i = 0; i < n; i++){cout << "Car #" << (i + 1) << ":\n";cout << "Please enter the make: ";cin.getline(pc[i].name,20);cout << "Please enter the year made: ";cin >> pc[i].year;while(cin.get() != '\n') // get rid of rest of line ;}cout << "Here is your collection:\n";for (i = 0; i < n; i++)cout << pc[i].year << " " << pc[i].name << "\n";delete [] pc;return 0;}// pe5-7.cpp -- count words using C-style string#include <iostream>#include <cstring> // prototype for strcmp()const int STR_LIM = 50;int main(){using namespace std;char word[STR_LIM];int count = 0;cout << "Enter words (to stop, type the word done):\n";while (cin >> word && strcmp("done", word))++count;cout << "You entered a total of " << count << " words.\n"; return 0;}// pe5-9.cpp//nested loops#include <iostream>int main(){using namespace std; //introduces namespace stdint rows;int row;int col;int periods;cout << "Enter number of rows: ";cin >> rows;for (row = 1; row <= rows; row++){periods = rows - row;for (col = 1; col <= periods; col++)cout << '.';// col already has correct value for next loop for ( ; col <= rows; col++)cout << '*';cout << endl;}return 0;}Chapter 6// pe6-1.cpp#include <iostream>#include <cctype>int main( ){using namespace std; //introduces namespace std char ch;cin.get(ch);while(ch != '@'){if (!isdigit(ch)){if (isupper(ch))ch = tolower(ch);else if (islower(ch))ch = toupper(ch);cout << ch;}cin.get(ch);}return 0;}// pe6-3.cpp#include <iostream>int main(void){using namespace std;cout << "Please enter one of the following choices:\n";cout << "c) carnivore p) pianist\n"<< "t) tree g) game\n";char ch;cin >> ch;while (ch != 'c' && ch != 'p' && ch != 't' && ch != 'g'){cout << "Please enter a c, p, t, or g: ";cin >> ch;}switch (ch){case 'c' : cout << "A cat is a carnivore.\n";break;case 'p' : cout << "Radu Lupu is a pianist.\n";break;case 't' : cout << "A maple is a tree.\n";break;case 'g' : cout << "Golf is a game.\n";break;default : cout << "The program shouldn't get here!\n"; }return 0;}// pe6-5.cpp// Neutronia taxation#include <iostream>const double LEV1 = 5000;const double LEV2 = 15000;const double LEV3 = 35000;const double RATE1 = 0.10;const double RATE2 = 0.15;const double RATE3 = 0.20;int main( ){using namespace std;double income;double tax;cout << "Enter your annual income in tvarps: ";cin >> income;if (income <= LEV1)tax = 0;else if (income <= LEV2)tax = (income - LEV1) * RATE1;else if (income <= LEV3)tax = RATE1 * (LEV2 - LEV1) + RATE2 * (income - LEV2);elsetax = RATE1 * (LEV2 - LEV1) + RATE2 * (LEV3 - LEV2)+ RATE3 * (income - LEV3);cout << "You owe Neutronia " << tax << " tvarps in taxes.\n";return 0;}// pe6-7.cpp#include <iostream>#include <string>int main(){using namespace std;string word;char ch;int vowel = 0;int consonant = 0;int other = 0;cout << "Enter words (q to quit):\n";cin >> word;while ( word != "q"){ch = tolower(word[0]);if (isalpha(ch)){if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')vowel++;elseconsonant++;}elseother++;cin >> word;}cout << vowel <<" words beginning with vowels\n";cout << consonant << " words beginning with consonants\n";cout << other << " others\n";return 0;}// pe6-8.cpp -- counting characters#include <iostream>#include <fstream> // file I/O suppport#include <cstdlib> // support for exit()const int SIZE = 60;int main(){using namespace std;char filename[SIZE];char ch;ifstream inFile; // object for handling file inputcout << "Enter name of data file: ";cin.getline(filename, SIZE);inFile.open(filename); // associate inFile with a fileif (!inFile.is_open()) // failed to open file{cout << "Could not open the file " << filename << endl;cout << "Program terminating.\n";exit(EXIT_FAILURE);}int count = 0; // number of items readinFile >> ch; // get first valuewhile (inFile.good()) // while input good and not at EOF{count++; // one more item readinFile >> ch; // get next value}cout << count << " characters in " << filename << endl;inFile.close(); // finished with the filereturn 0;}Chapter 7//pe7-1.cpp -- harmonic mean#include <iostream>double h_mean(double x, double y);int main(void){using namespace std;double x,y;cout << "Enter two numbers (a 0 terminates): ";while (cin >> x >> y && x * y != 0)cout << "harmonic mean of " << x << " and "<< y << " = " << h_mean(x,y) << "\n";/* or do the reading and testing in two parts:while (cin >> x && x != 0){cin >> y;if (y == 0)break;...*/cout << "Bye\n";return 0;}double h_mean(double x, double y){return 2.0 * x * y / (x + y);}// pe7-3.cpp#include <iostream>struct box {char maker[40];float height;float width;float length;float volume;};void showbox(box b);void setbox(box * pb);int main(void){box carton = {"Bingo Boxer", 2, 3, 5}; // no volume provided setbox(&carton);showbox(carton);return 0;}void showbox(box b){using namespace std;cout << "Box maker: " << b.maker<< "\nheight: " << b.height<< "\nlwidth: " << b.width<< "\nlength: " << b.length<< "\nvolume: " << b.volume << "\n";}void setbox(box * pb){pb->volume = pb->height * pb->width * pb->length;}// pe7-4.cpp -- probability of winning#include <iostream>long double probability(unsigned numbers, unsigned picks);int main(){using namespace std;double total, choices;double mtotal;double probability1, probability2;cout << "Enter total number of game card choices and\n""number of picks allowed for the field:\n";while ((cin >> total >> choices) && choices <= total){cout << "Enter total number of game card choices ""for the mega number:\n";if (!(cin >> mtotal))break;cout << "The chances of getting all " << choices << " picks is one in " << (probability1 = probability(total, choices) ) << ".\n";cout << "The chances of getting the megaspot is one in "<< (probability2 = probability(mtotal, 1) ) << ".\n";cout << "You have one chance in ";cout << probability1 * probability2; // compute the probabilitycout << " of winning.\n";cout << "Next set of numbers (q to quit): ";}cout << "bye\n";return 0;}// the following function calculates the probability of picking picks// numbers correctly from numbers choiceslong double probability(unsigned numbers, unsigned picks){long double result = 1.0; // here come some local variableslong double n;unsigned p;for (n = numbers, p = picks; p > 0; n--, p--)result = result * n / p ;return result;}// pe7-6.cpp#include <iostream>int Fill_array(double ar[], int size);void Show_array(const double ar[], int size);void Reverse_array(double ar[], int size);const int LIMIT = 10;int main( ){using namespace std;double values[LIMIT];int entries = Fill_array(values, LIMIT);cout << "Array values:\n";Show_array(values, entries);cout << "Array reversed:\n";Reverse_array(values, entries);Show_array(values, entries);cout << "All but end values reversed:\n";Reverse_array(values + 1, entries - 2);Show_array(values, entries);return 0;}int Fill_array(double ar[], int size){using namespace std;int n;cout << "Enter up to " << size << " values (q to quit):\n"; for (n = 0; n < size; n++){cin >> ar[n];if (!cin)break;}return n;}void Show_array(const double ar[], int size){using namespace std;int n;for (n = 0; n < size; n++){cout << ar[n];if (n % 8 == 7)cout << endl;elsecout << ' ';}if (n % 8 != 0)cout << endl;}void Reverse_array(double ar[], int size){int i, j;double temp;for (i = 0, j = size - 1; i < j; i++, j--){temp = ar[i];ar[i] = ar[j];ar[j] = temp;}}//pe7-9.cpp#include <iostream>double calculate(double x, double y, double (*pf)(double, double)); double add(double x, double y);double sub(double x, double y);double mean(double x, double y);int main(void){using namespace std;double (*pf[3])(double,double) = {add, sub, mean};char * op[3] = {"sum", "difference", "mean"};double a, b;cout << "Enter pairs of numbers (q to quit): ";int i;while (cin >> a >> b){// using function namescout << calculate(a, b, add) << " = sum\n";cout << calculate(a, b, mean) << " = mean\n";// using pointersfor (i = 0; i < 3; i++)cout << calculate(a, b, pf[i]) << " = "<< op[i] << "\n";}cout << "Done!\n";return 0;}double calculate(double x, double y, double (*pf)(double, double)) {return (*pf)(x, y);}double add(double x, double y){return x + y;}double sub(double x, double y){return x - y;}double mean(double x, double y){return (x + y) / 2.0;}Chapter 8// pe8-1.cpp#include <iostream>void silly(const char * s, int n = 0);int main(void){using namespace std;char * p1 = "Why me?\n";silly(p1);for (int i = 0; i < 3; i++){cout << i << " = i\n";silly(p1, i);}cout << "Done\n";return 0;}void silly(const char * s, int n){using namespace std;static int uses = 0;int lim = ++uses;if (n == 0)lim = 1;for (int i = 0; i < lim; i++)cout << s;}// pe8-4.cpp#include <iostream>#include <cstring> // for strlen(), strcpy()using namespace std;struct stringy {char * str; // points to a stringint ct; // length of string (not counting '\0')};void show(const char *str, int cnt = 1);void show(const stringy & bny, int cnt = 1);void set(stringy & bny, const char * str);int main(void){stringy beany;char testing[] = "Reality isn't what it used to be.";set(beany, testing); // first argument is a reference, // allocates space to hold copy of testing,// sets str member of beany to point to the// new block, copies testing to new block,// and sets ct member of beanyshow(beany); // prints member string onceshow(beany, 2); // prints member string twicetesting[0] = 'D';testing[1] = 'u';show(testing); // prints testing string onceshow(testing, 3); // prints testing string thrice show("Done!");return 0;}void show(const char *str, int cnt){while(cnt-- > 0){cout << str << endl;}}void show(const stringy & bny, int cnt){while(cnt-- > 0){cout << bny.str << endl;}}void set(stringy & bny, const char * str){bny.ct = strlen(str);bny.str = new char[bny.ct+1];strcpy(bny.str, str);}// pe8-5.cpp#include <iostream>template <class T>T max5(T ar[]){int n;T max = ar[0];for (n = 1; n < 5; n++)if (ar[n] > max)max = ar[n];return max;}const int LIMIT = 5;int main( ){using namespace std;double ard[LIMIT] = { -3.4, 8.1, -76.4, 34.4, 2.4};int ari[LIMIT] = {2, 3, 8, 1, 9};double md;int mi;md = max5(ard);mi = max5(ari);cout << "md = " << md << endl;cout << "mi = " << mi << endl;return 0;}Chapter 9PE 9-1// pe9-golf.h - for pe9-1.cppconst int Len = 40;struct golf{char fullname[Len];int handicap;};// non-interactive version// function sets golf structure to provided name, handicap // using values passed as arguments to the functionvoid setgolf(golf & g, const char * name, int hc);// interactive version// function solicits name and handicap from user// and sets the members of g to the values entered// returns 1 if name is entered, 0 if name is empty string int setgolf(golf & g);// function resets handicap to new valuevoid handicap(golf & g, int hc);// function displays contents of golf structurevoid showgolf(const golf & g);// pe9-golf.cpp - for pe9-1.cpp#include <iostream>#include "pe9-golf.h"#include <cstring>// function solicits name and handicap from user// returns 1 if name is entered, 0 if name is empty stringint setgolf(golf & g){std::cout << "Please enter golfer's full name: ";std::cin.getline(g.fullname, Len);if (g.fullname[0] == '\0')return 0; // premature terminationstd::cout << "Please enter handicap for " << g.fullname << ": "; while (!(std::cin >> g.handicap)){std::cin.clear();std::cout << "Please enter an integer: ";}while (std::cin.get() != '\n')continue;return 1;}// function sets golf structure to provided name, handicapvoid setgolf(golf & g, const char * name, int hc){std::strcpy(g.fullname, name);g.handicap = hc;}// function resets handicap to new valuevoid handicap(golf & g, int hc){g.handicap = hc;}// function displays contents of golf structurevoid showgolf(const golf & g){std::cout << "Golfer: " << g.fullname << "\n";std::cout << "Handicap: " << g.handicap << "\n\n";}// pe9-1.cpp#include <iostream>#include "pe9-golf.h"// link with pe9-golf.cppconst int Mems = 5;int main(void){using namespace std;golf team[Mems];cout << "Enter up to " << Mems << " golf team members:\n"; int i;for (i = 0; i < Mems; i++)if (setgolf(team[i]) == 0)break;for (int j = 0; j < i; j++)showgolf(team[j]);setgolf(team[0], "Fred Norman", 5);showgolf(team[0]);handicap(team[0], 3);showgolf(team[0]);return 0;}PE 9-3//pe9-3.cpp -- using placement new#include <iostream>#include <new>#include <cstring>struct chaff{char dross[20];int slag;};// char buffer[500]; // option 1int main(){using std::cout;using std::endl;chaff *p1;int i;char * buffer = new char [500]; // option 2p1 = new (buffer) chaff[2]; // place structures in buffer std::strcpy(p1[0].dross, "Horse Feathers");p1[0].slag = 13;std::strcpy(p1[1].dross, "Piffle");p1[1].slag = -39;for (i = 0; i < 2; i++)cout << p1[i].dross << ": " << p1[i].slag << endl;delete [] buffer; // option 2return 0;}Chapter 10PE 10-1// pe10-1.cpp#include <iostream>#include <cstring>// class declarationclass BankAccount{private:char name[40];char acctnum[25];double balance;public:BankAccount(char * client = "no one", char * num = "0",double bal = 0.0); void show(void) const; void deposit(double cash); void withdraw(double cash); };// method definitionsBankAccount::BankAccount(char * client, char * num, double bal)std::strncpy(name, client, 39);name[39] = '\0';std::strncpy(acctnum, num, 24);acctnum[24] = '\0';balance = bal;}void BankAccount::show(void) const{using std::cout;using std:: endl;cout << "Client: " << name << endl;cout << "Account Number: " << acctnum << endl;cout << "Balance: " << balance << endl;}void BankAccount::deposit(double cash){if (cash >= 0)balance += cash;elsestd::cout << "Illegal transaction attempted";}void BankAccount::withdraw(double cash){if (cash < 0)std::cout << "Illegal transaction attempted";else if (cash <= balance)balance -=cash;elsestd::cout << "Request denied due to insufficient funds.\n"; }// sample useint main(){BankAccount bird;BankAccount frog("Kermit", "croak322", 123.00);bird.show();frog.show();bird = BankAccount("Chipper", "peep8282", 214.00);bird.show();frog.deposit(20);frog.show();frog.withdraw(4000);frog.show();frog.withdraw(50);frog.show();}PE10-4// pe10-4.h#ifndef SALES__#define SALES__namespace SALES{const int QUARTERS = 4;class Sales{private:double sales[QUARTERS];double average;double max;double min;public:// default constructorSales();// copies the lesser of 4 or n items from the array ar// to the sales member and computes and stores the// average, maximum, and minimum values of the entered items; // remaining elements of sales, if any, set to 0Sales(const double ar[], int n);// gathers sales for 4 quarters interactively, stores them// in the sales member of object and computes and stores the // average, maximum, and minumum valuesvoid setSales();// display all information in objectvoid showSales();。
自测练习奇数题答案第1章1.1节1.软件1.2节1.存储单元0:75.625存储单元2:0.005存储单元999:75.623.位,字节,存储单元,主存储器,辅助存储器,LAN,WAN1.3节1.a、b、c的值相加,把和存储到x;y除以z,将结果存储到x;c减b,然后加a,将结果存储到d;z加1,并将结果存储到z;celsius加273.15,并将结果存储到kelvin。
3.源程序,编译器,编辑器(字处理器)1.4节1.问题需求,分析,设计,实现,测试和验证,维护1.5节1.算法细化(1) 获得以公里表示的距离。
(2) 把距离转化成英里。
2.1 用英里表示的距离是用公里表示的距离的0.621倍。
(3) 显示用英里表示的距离。
第2章2.1节1.a.void, double, returnb.printfc.MAX_ENTRIES, Gd.time, xyz123, this_is_a_long_onee.Sue's, part#2, "char", #include3.预处理器,#define和#include2.2节1.a. 0.0103 1234500.0 123450.0b. 1.3e+3 1.2345e+2 4.26e-33.double, int, char566自测练习奇数题答案2.3节1.Enter two integers> 5 7m = 10n = 213.My name is Jane Doe.I live in Ann Arbor, MIand I have 11 years of programming experience.2.4节1./* This is a comment? *//* This one seems like a comment doesn’t it */2.5节1.a. 22/7为37/22为022 % 7为1 7 % 22为7b. 16 / 15 为1 15 / 16为0 16 % 15为1 15 % 16为15c. 23 / 3 为7 3 / 23为0 23 % 3为2 3 % 23为3d. 16 / -3 为?? -3 / 16为?? 16 % -3为?? -3 % 16为??(??意为结果是变化的)3.a. 3g. 未定义m. -3.14159b. ?? h. 未定义n. 1.0c. 1 i. ?? o. 1d. -3.14159j. 3 p. 未定义e. ?? k. -3.0q. 3f. 0.0l. 9r. 0.75(??意为结果是变化的)5.a.white为1.6666… c.orange为0 e.lime为2b.green为0.6666…d.blue为-3.0 f.purple为0.02.6节1.printf("Salary is %10.2f\n",salary);3.x■is■■12.34■■i■is■100i■is■100x■is■12.32.7节1.在调用scanf获得数据之前先调用printf显示提示。
第一章概览编程练习1.您刚刚被MacroMuscle有限公司(Software for Hard Bodies)聘用。
该公司要进入欧洲市场,需要一个将英寸转换为厘米(1英寸=2.54 cm)的程序。
他们希望建立的该程序可提示用户输入英寸值。
您的工作是定义程序目标并设计该程序(编程过程的第1步和第2步)。
1.将英寸值转化为厘米值2.显示“输入英寸值”->得到该值->转换为厘米值->存储->告知用户已结束第二章 C语言概述编程练习1.编写一个程序,调用printf()函数在一行上输出您的名和姓,再调用一次printf()函数在两个单独的行上输出您的名和姓,然后调用一对printf()函数在一行上输出您的名和姓。
输出应如下所示(当然里面要换成您的姓名):Anton BrucknerAntonBrucknerAnton Bruckner第一个输出语句第二个输出语句仍然是第二个输出语句第三个和第四个输出语句#include<stdio.h>int main(void){printf("He Jin\n");printf("He\n");printf("Jin\n");printf("He Jin\n");return(0);}2.编写一个程序输出您的姓名及地址。
#include<stdio.h>int main(void){printf("Name:He Jin\n");printf("Address:CAUC\n");return(0);}3.编写一个程序,把您的年龄转换成天数并显示二者的值。
不用考虑平年( fractional year)和闰年(leapyear)的问题。
#include<stdio.h>int main(void){int age=22;printf("Age:%d\n",age);printf("Day:%d\n",age*356);return(0);}4.编写一个能够产生下面输出的程序:For he's a jolly good fellow!For he's a jolly good fellow!For he's a jolly good fellow!Which nobody can deny!程序中除了main()函数之外,要使用两个用户定义的函数:一个用于把上面的夸奖消息输出一次:另一个用于把最后一行输出一次。
一、单选题1. C语言中的三大基本数据类型包括( B )A.整型、实型、逻辑型B.整型、实型、字符型C.整型、逻辑型、字符型D.整型、实型、逻辑型、数组型2. 在C语言中,以下合法的字符常量是( C )A. '\048'B. 'ab'C. '\43'D. "\0"3.设x 为 int 型变量,执行下列语句: x=10; x+=x-=x-x; 则x的值为 ( B )A. 15B. 20C. 25D. 304.逗号表达式(a=3*5,a*4),a+15的值是( B )A.15B. 30C. 60D. 755. .以下程序的输出结果是( C )。
main( ){ int x=10,y=11;printf("%d,%d\n",x--,--y);}A. 11,11B. 10,11C. 10, 10D.11,106.设有变量说明:int a=7,b=8;那么语句:printf("%d,%d\n",(a+b,a),(b,a+b));的输出应该是( A )A. 7,15B. 8,15C. 15,7D.15,87. C语言变量名中不能使用的字符是( D )A. 数字B. 字母C. 下划线D. 关键字8.以下变量定义中合法的是( A )A.short a=2.1e-1;B. double b=1+5e0.5;C. long do=0xffe ;D. float 3_end=1-e3;9.若有说明语句char ch1=′\x79′;则ch1(D )A.包含4个字符B.包含3个字符C. 包含2个字符D.包含1个字符10. 设整形变量a=12;则执行完语句a+=a-=a*a后a的值为()A. 552B. 264C. -264D. 14411.设a=1,b=2,c=3,d=4,则表达式:a>b?a:c<d?a:d的结果是(A )A.1 B.2 C.3 D.412. 下面程序段执行结果是( B )int i=5,k; k=(++i)+(++i)+(i++); printf("%d,%d",k,i);A. 24,8B. 21,8C. 21,7D. 24,713.以下选项中属于C语言的数据类型是( B )。
第一章概览编程练习1.您刚刚被MacroMuscle(Software for Hard Bodies)聘用。
该公司要进入欧洲市场,需要一个将英寸转换为厘米(1英寸=2.54 cm)的程序。
他们希望建立的该程序可提示用户输入英寸值。
您的工作是定义程序目标并设计该程序(编程过程的第1步和第2步)。
1.将英寸值转化为厘米值2.显示“输入英寸值”->得到该值->转换为厘米值->存储->告知用户已结束第二章 C语言概述编程练习1.编写一个程序,调用printf()函数在一行上输出您的名和姓,再调用一次printf()函数在两个单独的行上输出您的名和姓,然后调用一对printf()函数在一行上输出您的名和姓。
输出应如下所示(当然里面要换成您的):Anton BrucknerAntonBrucknerAnton Bruckner第一个输出语句第二个输出语句仍然是第二个输出语句第三个和第四个输出语句#include<stdio.h>int main(void){printf("He Jin\n");printf("He\n");printf("Jin\n");printf("He Jin\n");return(0);}2.编写一个程序输出您的及地址。
#include<stdio.h>int main(void){printf("Name:He Jin\n");printf("Address:CAUC\n");return(0);}3.编写一个程序,把您的年龄转换成天数并显示二者的值。
不用考虑平年( fractional year)和闰年(leapyear)的问题。
#include<stdio.h>int main(void){int age=22;printf("Age:%d\n",age);printf("Day:%d\n",age*356);return(0);}4.编写一个能够产生下面输出的程序:For he's a jolly good fellow!For he's a jolly good fellow!For he's a jolly good fellow!Which nobody can deny!程序中除了main()函数之外,要使用两个用户定义的函数:一个用于把上面的夸奖消息输出一次:另一个用于把最后一行输出一次。
C语言程序设计教程第五章课后习题参考答案一、选择题1. B2. A3. C4. B5. D二、填空题1. while2. binary3. 164. 35. continue6. global三、判断题1. 错误2. 正确3. 错误4. 错误5. 正确四、编程题1.```c#include<stdio.h>int main() {int num;printf("请输入一个整数:"); scanf("%d", &num);if (num % 2 == 0) {printf("%d是偶数\n", num); } else {printf("%d是奇数\n", num); }return 0;}```2.```c#include<stdio.h>int main() {int num1, num2;printf("请输入两个整数:");scanf("%d %d", &num1, &num2);printf("%d与%d的和为%d\n", num1, num2, num1 + num2); return 0;}```3.```c#include<stdio.h>int isPrime(int num) {int i;if (num <= 1)return 0;for (i = 2; i <= num / 2; i++) {if (num % i == 0) {return 0;}}return 1;}int main() {int num;printf("请输入一个整数:");scanf("%d", &num);if (isPrime(num)) {printf("%d是素数\n", num); } else {printf("%d不是素数\n", num); }return 0;}```4.```c#include<stdio.h>int factorial(int num) {int i, result = 1;for (i = 1; i <= num; i++) {result *= i;}return result;}int main() {int num;printf("请输入一个整数:");scanf("%d", &num);printf("%d的阶乘为%d\n", num, factorial(num)); return 0;}```五、简答题1. C语言逻辑与运算符(&&)短路特性是什么?答:C语言逻辑与运算符(&&)具有短路特性,即在进行逻辑与运算时,如果前一个表达式的值为假(0),则后面的表达式将不会被计算,整个逻辑与表达式的值直接为假(0)。
第一章概览编程练习1.您刚刚被MacroMuscle有限公司(Software for Hard Bodies)聘用。
该公司要进入欧洲市场,需要一个将英寸转换为厘米(1英寸=2.54 cm)的程序。
他们希望建立的该程序可提示用户输入英寸值。
您的工作是定义程序目标并设计该程序(编程过程的第1步和第2步)。
1.将英寸值转化为厘米值2.显示“输入英寸值”->得到该值->转换为厘米值->存储->告知用户已结束第二章 C语言概述编程练习1.编写一个程序,调用printf()函数在一行上输出您的名和姓,再调用一次printf()函数在两个单独的行上输出您的名和姓,然后调用一对printf()函数在一行上输出您AHA12GAGGAGAGGAFFFFAFAF的名和姓。
输出应如下所示(当然里面要换成您的姓名):Anton BrucknerAntonBrucknerAnton Bruckner第一个输出语句第二个输出语句仍然是第二个输出语句第三个和第四个输出语句#include<stdio.h>int main(void){printf("He Jin\n");printf("He\n");printf("Jin\n");printf("He Jin\n");return(0);AHA12GAGGAGAGGAFFFFAFAF}AHA12GAGGAGAGGAFFFFAFAF2.编写一个程序输出您的姓名及地址。
#include<stdio.h>int main(void){printf("Name:He Jin\n");printf("Address:CAUC\n");return(0);}3.编写一个程序,把您的年龄转换成天数并显示二者的值。
不用考虑平年( fractional year)和闰年(leapyear)的问题。
C语言程序设计教程杨路明课后习题答案北京邮电大学出版社第一章1、算法描述主要是用两种基本方法:第一是自然语言描述,第二是使用专用工具进行算法描述2、c语言程序的结构如下:①c语言程序由函数组成,每个程序必须具有一个main函数作为程序的主控函数。
②"/*"与"*/"之间的内容构成c语言程序的注释部分。
③用预处理命令#include可以包含有关文件的信息。
④大小写字母在c语言中是有区别的。
⑤除main函数和标准库函数以外,用户可以自己编写函数,程序一般由多个函数组成,这些函数制定实际所需要做的工作。
例如:void main()int a,b,c,s;a=8;b=12;c=6;s=a b*c;printf("s=%d",s);3、c语言的特点:①c语言具有结构语言的特点,程序之间很容易实现段的共享;②c语言的主要结构成分为函数,函数可以在程序中被定义完成独立的任务,独立地编译成代码,以实现程序的模块化。
③c语言运算符丰富,运算包含的范围很广;④c语言数据类型丰富。
⑤c语言允许直接访问物理地址,即可直接对硬件进行操作,实现汇编语言的大部分功能;⑥c语言语法限制不太严格,程序设计自由度大,这样是c语言能够减少对程序员的束缚;⑦用c语言编程,生成的目标代码质量高,程序执行效率高,可移植性好;4、合法标识符:AB12、leed_3、EF3_3、_762、PAS、XYZ43K2不合法标识符:a*b2、8stu、D.K.Jon、if、ave#xy、#_DT5、C.D5、F2:将当前编辑器中文件存盘F10:调用主菜单F4:程序运行到光标所在行Ctrl F9:当前编辑环境下,进行编译、连接且运行程序;Alt F5:将窗口切换到DOS下,查看程序运行结果6、(1):********************welcome youvery good********************(2):please input three number;5,7,8max number is:87、main8、User screen、Alt F59、标识符必须是字母或下划线开头,大小写字母含义不同。
第一章1、8051单片机由哪几局部组成?8位中央处理器CPU、片内振荡电器及其时钟电路, 4个8位并行I/O口〔其中P0和P2可用于外部存储器的扩展〕,2个16位定时器/计数器,5个中断源〔具有2个中断优先级〕,全双工串行口,布尔处理器。
2、8051单片机有多少个特殊功能存放器?它们可以分为几组,各完成什么主要功能?P71-3表答:8051单片机内部有21个特殊功能存放器,在物理上是分散在片内各功能部件中,在数学上把它们组织在内部数据存储器地址空间80H~FFH中,以便能使用统一的直接寻址方式来访问。
这些特殊功能存放器颁在以下各个功能部件中:1〕CPU:ACC、B、PSW、SP、DPTR〔由DPL和DPH两个8位存放器组成〕;主要完成运算和逻辑判断功能;2〕中断系统:IP、IE;完成中断管理3〕定时器/计数器:TMOD、TCOM、TL0、TH0、TL1、TH1;完成定时或者计数功能〔4〕并行I/O口:P0、P1、P2、P3完成I/O口功能,其中局部I/O口带有可选的纵向拓展功能〔5〕串行口:SCON、SBUF、PCON。
主要完成数据的串行发送和接收3、决定程序执行顺序的存放器是哪几个?它是几位存放器?是否为特殊功能存放器?它的内容是什么信息?是程序计数器PC,它是16位存放器,不是特殊功能存放器,它的内容是下一条将要执行的程序的地址4、DPTR是什么特殊功能存放器?DPTR的用途是什么?它由哪几个特殊功能存放器组成?DPTR是16位数据指针存放器,它由两个8位特殊功能存放器DPL〔数据指针低8位〕和DPH〔数据指针高8位〕组成,DPTR用于保存16位地址,作地址存放器用,可寻址外部数据存储器,也可寻址程序存储器。
5、8051的引脚有多少I/O线?它们和单片机对外的地址总线和数据总线有什么关系?地址总线和数据总线各是多少位?8051单片机的40个引脚中有32根I/O口线,P0口8根I/O线可以在外扩存储器时分时复用作为外部存储器的低8位地址总线和8位数据总线,P2口作为高P3.7分别作为外部存储器的写和读控制线。
c语言入门经典第5版习题答案C语言入门经典第5版习题答案C语言作为一门广泛应用于计算机科学和软件开发领域的编程语言,具有简洁、高效和灵活的特点。
《C语言入门经典》是一本经典的教材,对于初学者来说是学习C语言的良好起点。
本文将为读者提供《C语言入门经典》第5版的习题答案,帮助读者更好地巩固所学知识。
第一章:C语言基础知识1.1 变量和数据类型1. 在C语言中,变量的命名规则是以字母或下划线开头,后面可以跟字母、数字或下划线。
变量名不能以数字开头,也不能使用C语言的关键字作为变量名。
2. C语言提供了多种数据类型,包括整型、浮点型、字符型等。
整型可以分为有符号和无符号两种,浮点型可以分为单精度和双精度两种。
3. 常见的数据类型转换包括隐式类型转换和显式类型转换。
隐式类型转换是自动进行的,而显式类型转换需要使用强制类型转换运算符。
1.2 运算符和表达式1. C语言中的运算符包括算术运算符、关系运算符、逻辑运算符等。
算术运算符用于进行基本的数学运算,关系运算符用于比较两个值的大小关系,逻辑运算符用于进行逻辑判断。
2. 表达式是由运算符和操作数组成的。
C语言中的表达式可以包含常量、变量、函数调用等。
3. 运算符的优先级决定了表达式中各个运算符的执行顺序。
在表达式中可以使用括号来改变运算符的优先级。
第二章:控制语句2.1 分支语句1. C语言中的分支语句包括if语句、switch语句等。
if语句用于根据条件执行不同的代码块,switch语句用于根据表达式的值选择执行不同的代码块。
2. 在if语句中,可以使用if-else语句来处理多个条件。
在switch语句中,可以使用break语句来跳出switch语句的执行。
2.2 循环语句1. C语言中的循环语句包括while循环、do-while循环和for循环。
while循环用于在满足条件的情况下重复执行一段代码,do-while循环先执行一次代码,再根据条件判断是否继续执行,for循环在一定条件下重复执行一段代码。
c语言程序设计第五版习题答案解析首先,值得指出的是,《C语言程序设计》是一本经典的编程教材,它通过系统性的介绍和练习,帮助读者掌握C语言编程的基本原理和
技巧。
而针对这本书中的习题,我们将逐一进行解答和解析,以便读
者更好地理解和掌握其中的知识。
1. 第一章:C语言概述
在第一章中,主要介绍了C语言的历史背景、特点和发展。
对于习
题的解答,我们可以通过提问的方式帮助读者思考和回顾所学内容,
例如:“C语言为什么被广泛应用于系统软件开发?”、“C语言的起源
是什么?”
2. 第二章:数据类型、运算符和表达式
在第二章中,主要介绍C语言中的数据类型、运算符和表达式。
习
题部分则涵盖了类型转换、算术运算、逻辑运算等内容。
针对这些习题,我们可以给出详细的解答步骤和原理解析,让读者了解C语言中
各种运算符的优先级和使用规则。
3. 第三章:控制结构
第三章主要介绍了C语言中的分支结构和循环结构。
针对习题部分,我们可以详细解答条件语句、循环语句的使用和注意事项,同时提供
一些实际例子和应用场景,让读者更好地理解和掌握这些知识点。
4. 第四章:函数与程序结构
在第四章中,重点介绍了函数的定义、调用和参数传递等。
针对习题,我们可以通过编写代码的方式,给出函数的实际应用案例,并解释其中的关键代码部分,帮助读者理解函数的作用和使用方法。
5. 第五章:指针与数组
第五章主要介绍了C语言中指针和数组的概念和用法。
对于习题解答,我们可以给出指针和数组的定义、操作方法,并通过实例演示指针和数组在实际编程中的应用。
6. 第六章:字符输入输出
第六章主要讲解了C语言中字符输入输出的函数和特点。
在解答习题时,我们可以提供一些常见的字符输入输出问题,并给出详细的解决思路和代码示例。
7. 第七章:类型
第七章主要介绍了C语言中的类型定义和使用。
对于习题解答,我们可以通过解析代码和理论知识的结合,帮助读者理解类型的定义和使用场景。
8. 第八章:运算符和表达式
在第八章中,主要介绍了C语言中的运算符和表达式。
对于习题解答,我们可以通过编写实例代码,演示运算符在表达式中的使用和计算过程,同时讲解运算符的优先级和结合性等相关知识点。
9. 第九章:位运算
第九章主要介绍了C语言中的位运算符和位操作。
在解答习题时,我们可以通过实例代码和位运算的原理解析,帮助读者理解位运算的含义和使用方法。
10. 第十章:输入输出重定向
第十章讲解了C语言中的输入输出重定向,主要包括标准输入输出函数和文件输入输出函数的使用。
针对习题解答,我们可以提供常见的输入输出重定向问题,并给出解决思路和代码实例。
通过以上的习题解答和知识解析,读者能够更加全面地掌握C语言程序设计中的知识和技巧,提高编程能力和理解能力。
希望本文对您有所帮助!。