C程序设计第五章课后习题答案
C语言程序设计课后各章节习题答案
![C语言程序设计课后各章节习题答案](https://img.taocdn.com/s3/m/0adfacfa700abb68a982fbe1.png)
main()
{
float x,y,d;
printf("Input x,y:");
scanf("%f,%f",&x,&y);
d=sqrt((x-2)*(x-2)+(y-2)*(y-2));
if(d>1)printf(ntf("inside");
}
12有一函数
x-1 -5<x<0
y= x x=0
x+1 0<x<8
编写一程序,要求输入x的值,输出y的值。分别用不嵌套的if语句,嵌套的if语句,switch语句编写。
答使用不嵌套的if语句程序如下:
main()
{
int x,y;
printf("Input x:");
scanf("%d",&x);
答main()
{
int x,a,b,c;
printf("Input number:");
scanf("%d",&x);
a=x/100;/*变量a中记录x的百倍数字*/
b=x/10%10;/*变量b中记录x的十位数字*/
c=x%10;/*变量c中记录x的个位数字*/
if(a*a*a+b*b*b+c*c*c==x)
if(m==2)
d=28+f;
else
d=31-(m==4)+(m==6)+(m==9)+(m==11);
printf("%d-%d is %d days.\n",y,m,d);
C++程序设计基础课后答案 第五章
![C++程序设计基础课后答案 第五章](https://img.taocdn.com/s3/m/04fa0ed3240c844769eaeea5.png)
5.1 阅读下列程序,写出执行结果1.#include < iostream.h >struct data{ int n ;float score ;} ;void main(){ data a[3] = { 1001,87,1002,72,1003,90 } , *p = a ; cout << (p++)->n << endl ;cout << (p++)->n << endl ;cout << p->n++ << endl ;cout << (*p).n++ << endl ;}2.#include < iostream.h >struct employee{ char name[ 20 ] ;char sex ;} ;void fun( employee *p ){ if( (*p).sex == 'm' )cout << (*p).name << endl ;}void main(){ employee emp[5] = { "Liming", 'm', "Wangxiaoping", 'f', "Luwei", 'm' } ; int i ;for( i=0; i<3; i++ )fun( emp+i ) ;}3. #include < iostream.h >struct node{ char * s ;node * q ;} ;void main(){ node a[ ] = { { "Mary", a+1 }, { "Jack", a+2 }, { "Jim", a } } ;node *p = a ;cout << p->s << endl ;cout << p->q->s << endl ;cout << p->q->q->s << endl ;cout << p->q->q->q->s << endl ;}4.#include < iostream.h >class A{ public :int f1();int f2();void setx( int m ) { x = m ; cout << x << endl; } void sety( int n ) { y = n ; cout << y << endl; } int getx() { return x ; }int gety() { return y ; }private :int x, y ;};int A::f1() { return x + y ; }int A::f2() { return x - y ; }void main(){ A a ;a.setx( 10 ) ; a.sety( 5 ) ;cout << a.getx() << '\t' << a.gety() << endl ;cout << a.f1() << '\t' << a.f2() << endl ;}5. #include < iostream.h >class T{ public :T( int x, int y ){ a = x ; b = y ;cout << "调用构造函数1." << endl ;cout << a << '\t' << b << endl ;}T( T &d ){ cout << "调用构造函数2." << endl ;cout << d.a << '\t' << d.b << endl ;}~T() { cout << "调用析构函数."<<endl; }int add( int x, int y = 10 ) { return x + y ; } private :int a, b ;};void main(){ T d1( 4, 8 ) ;T d2( d1 ) ;cout << d2.add( 10 ) << endl ;}6. #include < iostream.h >class T{ public:T(int x){ a=x; b+=x;};static void display(T c){ cout<<"a="<<c.a<<'\t'<<"b="<<c.b<<endl; }private:int a;static int b;} ;int T::b=5;void main(){ T A(3),B(5);T::display(A);T::display(B);}7. #include < iostream.h >#include < math.h >class point{ public :point( float x, float y ){ a = x; b = y;? cout << "点( " << a << ", " << b << " )" ; }friend double d( point &A , point &B ){ return sqrt((A.a-B.a) * (A.a-B.a) + (A.b-B.b) * (A.b-B.b)) ; } private:double a, b ;};void main(){ point p1( 2, 3 ) ;cout << " 到 " ;point p2( 4, 5 ) ;cout << "的距离是:" << d( p1,p2 ) << endl ;}8. #include < iostream.h >class A{ public :A() { a = 5 ; }void printa() { cout << "A:a = " << a << endl ; }private :int a ;friend class B ;} ;class B{ public:void display1( A t ){ t.a ++ ; cout << "display1:a = " << t.a << endl ; } ; void display2( A t ){ t.a -- ; cout << "display2:a = " << t.a << endl ; } ; };void main(){ A obj1 ;B obj2 ;obj1.printa() ;obj2.display1( obj1 ) ;obj2.display2( obj1 ) ;obj1.printa() ;}5.2 思考题1.结构和类有什么区别?如果把程序中定义结构的关键字struct直接改成class,会有什么问题?用教材上的一个例程试一试,想一想做什么修改能使程序正确运行?2.分析以下说明结构的语句struct node{ int data;node error; //错误node * ok; //正确};error和ok分别属于什么数据类型?有什么存储要求?error出错的原因是什么?3.有说明class A{ int a;double x;public:funMember();};A a1, a2, a3 ;编译器为对象a1,a2,a3开辟了什么内存空间?它们有各自的funMember函数的副本吗?C++通过什么机制调用类的成员函数?4.C++提供了默认版本的构造函数,为什么还需要用户自定义构造函数?编写一个验证程序,说明自定义构造函数的必要性。
程序设计基础课后答案 第五章
![程序设计基础课后答案 第五章](https://img.taocdn.com/s3/m/76654b5b3b3567ec102d8a32.png)
int i,m,n;
m=strlen(dest);
n=strlen(a)-m;
try//用于抛出错误
{
for(i=0;i<=n;i++)
{
int k=i;/r(int j=0;j<=m-1;j++)
{
if(a[k]==dest[j])
cout<<"values after function"<<big<<"and"<<small<<endl;
}
分析:输出结果:Values before function 2002 and 0
Values after function 2002 and 0
在函数调用中,可以通过值传递方式在函数间传递数据。但是,这种传递无法改变实参的值。只是因为在进入被调用函数时,变量进行了复制。被调用函数的任何更改和实参没有任何联系。所以,在主程序中打印它的局部变量时,变量值没有任何改变。
double add(double,double);
void main()
{
cout<<add(5,10)<<endl;
cout<<add(5.0,10.6)<<endl;
}
int add(int x,int y)
{
return x+y;
}
double add(double a, double b)
四、编程题
2、编写一个函数,在一个字符串数组中查找"Hello",如果找回返回指向“Hello”开始出的指针;否则抛出一个异常“Not Found”.
《C语言程序设计教程》第三版课后习题参考答案
![《C语言程序设计教程》第三版课后习题参考答案](https://img.taocdn.com/s3/m/d26c4b9077a20029bd64783e0912a21615797f7e.png)
《C语言程序设计教程》第三版课后习题参考答案C语言程序设计教程第三版课后习题参考答案第一章:C语言概述1.1 C语言的特点答案:C语言是一种通用的、面向过程的程序设计语言,具有高效、简洁、灵活等特点。
它提供了丰富的程序设计元素和功能,适用于各种不同的应用领域。
1.2 C语言程序的基本结构答案:C语言程序由预处理指令、函数声明、函数定义、变量声明和语句组成。
其中,预处理指令用来引入头文件或定义宏,函数声明用来声明函数的名称和参数,函数定义用来实现函数的功能,变量声明用来声明变量的类型和名称,语句用来表达具体的计算过程。
1.3 C语言的数据类型答案:C语言提供了多种数据类型,包括基本类型(整型、浮点型、字符型等)和派生类型(数组、指针、结构体等)。
每种数据类型在内存中占据一定的存储空间,并具有特定的取值范围和操作规则。
1.4 C语言的运算符和表达式答案:C语言支持各种运算符和表达式,例如算术运算符(+、-、*、/等)、关系运算符(>、<、==等)、逻辑运算符(&&、||、!等)等。
通过运算符和表达式可以进行各种数值计算和逻辑判断。
第二章:基本数据类型与运算2.1 整型数据类型答案:C语言提供了不同长度的整型数据类型,包括有符号整型(int、long等)和无符号整型(unsigned int、unsigned long等)。
整型数据类型可以表示整数值,并具有不同的取值范围。
2.2 浮点型数据类型答案:C语言提供了浮点型数据类型(float、double等),用来表示带小数部分的实数值。
浮点型数据可以表示较大或较小的数值,并具有一定的精度。
2.3 字符型数据类型答案:C语言提供了字符型数据类型(char),用来表示单个字符。
字符型数据可以用于表示各种字符(包括字母、数字、符号等)。
2.4 布尔型数据类型答案:C语言不直接支持布尔型数据类型,但可以使用整型数据类型来表示布尔值(0表示假、非零表示真)。
C语言程序设计教程 第五章 课后习题参考答案
![C语言程序设计教程 第五章 课后习题参考答案](https://img.taocdn.com/s3/m/0cc61576f5335a8102d220fc.png)
k++;
if(k%5==0)
printf("\n");
f1=f2;
f2=f;
}
printf("\n");
return 0;
}
P124 3统计一个整数的位数
#include<stdio.h>
int main()
{
int n,k=0;
printf("请输入n的值:");
int main()
{
int x,y,z,i=0;
for(x=1;x<=20;x++)
{
for(y=1;y<=33;y++)
{
for(z=3;z<=99;z=z+3)
{
if((5*x+3*y+z/3==100)&&(x+y+z==100))
i++;
}
}
}
printf("共有%d种买法:\n",i);
c语言程序设计教程第五章课后习题参考答案
P1242古典问题:兔子总数(斐波那契数列)
#include<stdio.h>
int main()
{
int f1=1,f2=1,f,i,k=0;
printf("%d\t %d\t",f1,f2);
k=k+2;
for(i=3;i<=20;i++)
{
f=f1+f2;
do
{
printf("请输入第%d个整数x=",i);
《C语言程序设计》教材习题答案第5章
![《C语言程序设计》教材习题答案第5章](https://img.taocdn.com/s3/m/155004047275a417866fb84ae45c3b3567ecddc1.png)
《C语言程序设计》教材习题答案第5章一、选择题1.设有程序段”int k=10;while(k=0)k=k-1;”,则下面叙述正确的是D 循环体语句一次也不执行2.设有程序段”int x=0,s=0;while(!x!=0)s+=++x;printf(“%d”,s);”则A 运行程序段后输出13.若有语句”int x=3;do{printf(“%d\n”,x-=2);}while(!(--x));”,则该程序段C 输出的是1和-24.下面循环语句中,错误的是D int a=1,b=2;do b--while(b= =0);5.已知”int i=5;”,下列do…while循环语句的循环次数为C 5do{printf(“%d\n”,i--);}while(i!=0);6.循环语句”for(int i=0,j=10;i=j=10;i++,j--)”的循环次数是D 无限7.循环语句”while(int i=0;)i--;”的循环次数是A 08.下述有关break语句的描述中,不正确的是C break语句用于if 语句的内嵌语句内,它结束该if语句9.下面关于循环语句的描述中,错误的是B 循环体内必须同时出现break语句和continue语句10.以下不是死循环的是 D for(;(c=getchar()!=’\n’);)printf(“%c”,c);11.执行语句”for(i=0;i++<3;);”后,变量i的值为C 412.语句”for(x=0,y=0;y!=1&&x<4;x++);”是C 循环4次13.与语句”while(!x);”等价的语句是A while(x= =0);14.执行下列程序段后a的值为B 2int a=1,b=10;do{b-=a;a++;}while(b--<0)二、编程题1.读入用户输入的6个整数并显示其平均值。
#includemain(){float sum=0;int tmp;int i;for(i=0;i<6;i++){printf("输入第%d个数:",i+1);scanf("%d",&tmp);sum=sum+tmp;}printf("平均值是:%f",sum/6);}2.先读入一个正整数n,然后计算并显示前n个偶数的和。
c语言选择程序设计(第五章)习题答案
![c语言选择程序设计(第五章)习题答案](https://img.taocdn.com/s3/m/a936270e76c66137ee0619c3.png)
}*/
//*****采用switch语句编写*****//
void main()
{
long i;
float bonus;
scanf("%ld",&i);
int g=i/100000;
switch(g)
else if(i<=1000000)
bonus=(i-600000)*0.015+200000*0.03+200000*0.05+100000*0.075+100000*0.1; //bonus=(i-600000)*0.015+bonus6;
else
bonus=(i-1000000)*0.01+400000*0.015+200000*0.03+200000*0.05+100000*0.075+100000*0.1; //bonus=(i-1000000)*0.01+bonus10;
bonus=(i-200000)*0.05+100000*0.075+100000*0.1; //bonus=(i-200000)*0.05+bonus2;
else if(i<=600000)
bonus=(i-400000)*0.03+200000*0.05+100000*0.075+100000*0.1; //bonus=(i-400000)*0.03+bonus4;
case 9:
bonus=(i-600000)*0.015+200000*0.03+200000*0.05+100000*0.075+100000*0.1;//bonus=(i-600000)*0.015+bonus6;
C程序设计(第四版)谭浩强第5章习题答案
![C程序设计(第四版)谭浩强第5章习题答案](https://img.taocdn.com/s3/m/3a92d8c54028915f804dc2b5.png)
5.2#include<stdio.h>#include<math.h>int main(){int sign=1,i=0;double pi=0.0,n=1.0,term=1.0; while(fabs(term)>=1e-6){pi=pi+term;n=n+2;sign=-sign;term=sign/n;i++;}pi=pi*4;printf("i=%d\npi=%10.8f\n",i,pi); return 0;}5.2#include<stdio.h>#include<math.h>int main(){int sign=1,i=0;double pi=0.0,n=1.0,term=1.0; while(fabs(term)>=1e-8){pi=pi+term;n=n+2;sign=-sign;term=sign/n;i++;}pi=pi*4;printf("i=%d\npi=%10.8f\n",i,pi); return 0;}5.3#include<stdio.h>int main(){int m,n,t,q,r;printf("输入两个正整数:"); scanf("%d,%d",&m,&n);if(m<n){ t=m;m=n;n=t;}q=m*n;while(n!=0){ r=m%n;m=n;n=r;}printf("最大公约数:%d\n",m); printf("最小公倍数:%d\n",q/m); yreturn 0;}5.4#include<stdio.h>int main(){int letter=0,space=0,digit=0,other=0;char c;printf("输入一行字符:\n");while((c=getchar())!='\n'){if(c>='a'&&c<='z'||c>='A'&&c<='Z')letter++;else if(c==' ')space++;else if(c>='0'&&c<='9')digit++;elseother++;}printf("英文字母个数:%d\n空格个数:%d\n 数字个数:%d\n其他:%d\n",letter,space,digit,other);return 0;}5.5#include<stdio.h>int main(){int n,i,a,t=0,s=0;printf("input a,n=");scanf("%d,%d",&a,&n);for(i=1;i<=n;i++){t=t+a;s=s+t;a=10*a;}printf("a+aa+aaa+……+aa……a=%d\n",s); return 0;}5.6#include<stdio.h>int main(){double n,t=1,s=0;for(n=1;n<=20;n++){t=t*n;s=s+t;}printf("结果为:%25.15e",s); return 0;}5.7#include<stdio.h>int main(){float s3=0,k;int s1=0,s2=0;for(k=1;k<=100;k++){s1=s1+k;}for(k=1;k<=50;k++){s2=s2+k*k;}for(k=1;k<=10;k++){s3=1/k+s3;}printf("%d\n%d\n%15.6f\n%15.6f\n",s1,s2,s3, s1+s2+s3);return 0;}5.8#include<stdio.h>int main(){int a,b,s,g;for(a=100;a<=999;a++){b=a/100;s=(a-b*100)/10;g=a-b*100-s*10;if(a==b*b*b+s*s*s+g*g*g)printf("%d\n",a);}printf("\n");return 0;}5.9#include<stdio.h>int main(){ int m,s,i;for(m=2;m<1000;m++){ s=0;for(i=1;i<m;i++)if((m%i)==0)s=s+i;if(s==m){ printf("%d its factors are",m);for(i=1;i<m;i++)if(m%i==0) printf("%d ",i);printf("\n");}}return 0;}5.10#include<stdio.h>int main(){float a=2,b=1,t,s=0;int i;for(i=1;i<=20;i++){ s=s+a/b;t=a;a=a+b;b=t;}printf("sum=%15.12f\n",s);return 0;}5.11#include<stdio.h>int main(){int i;float s=0,l=100,h=l/2;for(i=1;i<=10;i++){s=s+2*h;h=h/2;}printf("共经过:%f\n第10次反弹:%f\n",s,h);return 0;}12.#include<stdio.h>int main(){int i,a=1;for(i=9;i>0;i--)a=2*a+2;printf("%d\n",a);return 0;}#include<stdio.h>int main(){int i,j,k;for(i=0;i<=3;i++){ for(j=0;j<3-i;j++)printf(" ");for(k=0;k<=2*i;k++)printf("*");printf("\n");}for(i=0;i<=2;i++){ for(j=0;j<=i;j++)printf(" ");for(k=0;k<=4-2*i;k++)printf("*");printf("\n");}return 0;}#include <stdio.h>int main(){char i,j,k;for(i='x';i<='z';i++)for(j='x';j<='z';j++)if(i!=j)for(k='x';k<='z';k++)if(i!=k&&j!=k)if(i!='x'&&k!='x'&&k!='z')printf("A-%c\nB-%c\nC-%c\n"<i,j,k); return 0;}。
C语言程序设计教程 第五章 课后习题参考答案
![C语言程序设计教程 第五章 课后习题参考答案](https://img.taocdn.com/s3/m/4c57f037f68a6529647d27284b73f242336c31b9.png)
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)。
C++程序设计Y.Daniel Liang 第五章课后习题答案
![C++程序设计Y.Daniel Liang 第五章课后习题答案](https://img.taocdn.com/s3/m/fe405f3b67ec102de2bd892f.png)
}
return result;
}
int main()
{
cout << reverse(12345) << endl;
return 0;
}
Exercise5_6
#include <iostream>
using namespace std;
void displayPattern(int n)
{
return (9.0 / 5.0) * celsius + 32;
}
double fahrenheitToCelsius(double fahrenheit)
{
return (5.0 / 9) * (fahrenheit - 32);
}
int main()
{
cout << setw(12) << "Celsius" << setw(12) << "Fahrenheit" << setw(12) << "|" <<
for (int i = 1; i <= 10; celsius--, farenheit -= 10, i++)
{
cout << setw(12) << celsius << setw(12) << celsiusToFahrenheit(celsius) <<
setw(12) << "|" << setw(12) << farenheit << setw(12) << setprecision(5) << showpoint << fahrenheitToCelsius(farenheit) << endl;
C++语言程序设计(清华大学出版社)课后习题及答案 第 五 章 程序的结构
![C++语言程序设计(清华大学出版社)课后习题及答案 第 五 章 程序的结构](https://img.taocdn.com/s3/m/c4de55d676eeaeaad1f3302d.png)
void TelepathicFunction(); int main() { const int MaxCats = 5; Cat *CatHouse[MaxCats]; int i; for (i = 0; i<MaxCats; i++) { CatHouse[i] = new Cat(i); TelepathicFunction(); } for ( i = 0; i<MaxCats; i++) { delete CatHouse[i]; TelepathicFunction(); } return 0; } void TelepathicFunction() { cout << "There are " << Cat::GetHowMany() << " cats alive!\n"; } 程序运行输出: There are 1 cats alive! There are 2 cats alive! There are 3 cats alive! There are 4 cats alive! There are 5 cats alive! There are 4 cats alive! There are 3 cats alive! There are 2 cats alive! There are 1 cats alive! There are 0 cats alive!
5-8 什么叫做友元函数?什么叫做友元类?
解: 友元函数是使用 friend 关键字声明的函数,它可以访问相应类的保护成员和私有成员。友元 类是使用 friend 关键字声明的类,它的所有成员函数都是相应类的友元函数。
本页已使用福昕阅读器进行编辑。 福昕软件(C)2005-2009,版权所有, 仅供试用。
《C面向对象程序设计答案解析》-第五章谭浩强-清华大学出版社.docx
![《C面向对象程序设计答案解析》-第五章谭浩强-清华大学出版社.docx](https://img.taocdn.com/s3/m/107b862daeaad1f347933f69.png)
1:#include <iostream>using namespace std;class Student{public:void get_value(){cin>>num>>name>>sex;}void display( ){cout<<"num: "<<num<<endl;cout<<"name: "<<name<<endl;cout<<"sex: "<<sex<<endl;} private :int num;char name[10];char sex;};class Student1: public Student {public:void get_value_1(){get_value();cin>>age>>addr;}void display_1(){cout<<"age: "<<age<<endl;// 引用派生类的私有成员,正确。
cout<<"address: "<<addr<<endl;}// 引用派生类的私有成员,正确。
private:int age;char addr[30];};int main(){Student1 stud1;stud1.get_value_1();stud1.display();stud1.display_1();return 0;}2:#include <iostream>using namespace std;class Student{public:void get_value(){cin>>num>>name>>sex;}void display( ){cout<<"num: "<<num<<endl;cout<<"name: "<<name<<endl;cout<<"sex: "<<sex<<endl;}private :int num;char name[10];char sex;};class Student1: private Student{public:void get_value_1(){get_value();cin>>age>>addr;}void display_1(){display();cout<<"age: "<<age<<endl;// 引用派生类的私有成员,正确。
C++程序设计(第2版)课后第五章习题解答
![C++程序设计(第2版)课后第五章习题解答](https://img.taocdn.com/s3/m/d50b8d6948d7c1c708a1457b.png)
答案:(1)类型
(2)数量
(3)下标运算符
(4)下标
(5)索引
(6)常变量
5.1.2 C/C++中的多维数组用的是一个的定义,即多维数组的基本定义是成的数组,三维数组的元素是 (3) 。
答案:(1)嵌套
(2)以数组作为元素
(3)二维数组
5.1.3 计算机内存是一维编址的,多维数组在内存中的存储 (1) ,C/C++多维在内存中
第五章 数组与指针习题 1
第五章 数组与指针习题填充题
5.1.1 数组定义时有三个要素:数组名,数组元素的和数组元素的。按元
素在数组中的位置进行访问,是通过 (3) 进行的,称为 (4) 或 (5) 访问。
为了使数组声明中数组的大小修改更为方便,总是将 (6) 用于声明数组长度。
5.1.4 的大小是确定的,所谓“不检查数组边界”只是不检查
的边界,而 (3) 的边界是在控制之中的,所以多维数组名作为函数的参数只可以
(4) 缺省。
答案:(1)较低各维的
(2)最高维(第一维)
(3)较低各维
(4)最高维
5.1.5 指针变量保存了另一变量的值,不可以任意给指针变量赋一个地址值,只能赋
给它 (2) 和 (3) 的地址。使用变量名来访问变量,是按 (4) 来直接存取变
量称为 (5) 方式;而借助指针变量取得另一变量的地址,访问该变量称为 (6) 方式。
答案:(1)地址
(2)NULL
的排列是 (2) 方式,即越 (3) 的下标变化 (4) 。设数组a有m行n列,每
个元素占内存u个字节,则a[i][j]的首地址为 (5) + (6) 。
c程序设计第五章课后答案
![c程序设计第五章课后答案](https://img.taocdn.com/s3/m/c617b3f94693daef5ef73dc2.png)
else if (c>='0' && c<='9')
digit++;
else
other++;
}
printf("字母数:%d\n空格数:%d\n数字数:%d\n其它字符数:%d\n",letters,space,digit,other);
return 0;
}
5-5
#include <stdio.h>
{s2=s2+k*k;}
for (k=1;k<=n3;k+&3+1/k;}
printf("sum=%15.6f\n",s1+s2+s3);
return 0;
}
5-8
#include <stdio.h>
int main()
{
int i,j,k,n;
printf("parcissus numbers are ");
n=m;
m=temp;
}
p=n*m;
while(m!=0)
{
r=n%m;
n=m;
m=r;
}
printf("它们的最大公约数为:%d\n",n);
printf("它们的最小公约数为:%d\n",p/n);
return 0;
}
5-4
#include <stdio.h>
int main()
{
char c;
return 0;
}
5-7
面向对象的C++程序设计 第六版 课后习题答案第五章
![面向对象的C++程序设计 第六版 课后习题答案第五章](https://img.taocdn.com/s3/m/ee30af30b90d6c85ec3ac626.png)
Chapter 5Functions for All Subtasks1. Solutions to Selected Programming ProjectsDetailed solutions to the first 6 projects are presented here. The rest are essentially thesame problems, except for what is being converted. Notes about the remaining problemsare included.One of the more important things in programming is planning, even for the simplest program. If the planning is thorough, the coding will be easy, and the only errors likely tobe encountered are syntax errors, usually caused by either typing errors, a boundary condition problem (frequently, an off by one error), or (we hope not) lack of knowledge of the language details.1 Convert TimeTask: Convert 24 hour time notation to 12 hour AM/PM notation. General comments: The student should note that:a) The convert function has boundary cases that require careful attention.b) ALL of this commentary and planning should be done PRIOR to beginning to write the program. Once this is done the program is almost written. The sooner coding begins, the longer the program will take to do correctly.c) When testing for equality, as inif (12 == hours)put the constant first. The compiler will catch errors such as if (12= hours) which are hardto see otherwise. I made many errors of this type while coding this problem.1//file: //Task: Convert 24 hour time notation to 12 hour AM/PM//notation.//Input: 24 hour time//Output: corresponding 12 hour time, with AM/PM indication //Required: 3 functions: input, conversion, and output.// keep AM/PM information in a char variable// allow repeat at user's option//Notes: conversion function will have a char reference// parameter to return whether the time is AM/PM. Other// parameters are required.#include <iostream>using namespace std;void input( int& hours24, int& minutes);//Precondition: input( hours, minutes ) is called with//arguments capable of being assigned.//Postcondition:// user is prompted for time in 24 hour format:// HH:MM, where 0 <= HH < 24, 0 <= MM < 60.// hours is set to HH, minutes is set to MM.//KNOWN BUG: NO CHECKING IS DONE ON INPUT FORMAT. Omitting//the “:” (colon) from the input format “eats” one character //from the minutes data, and silently gives erroneous//results.void convert( int& hours, char& AMPM );//Precondition: 0 <= hours < 24,//Postcondition:// if hours > 12, // Note: definitely in the afternoon// hours is replaced by hours - 12,// AMPM is set to 'P'// else if 12 == hours // boundary afternoon hour // AMPM is set to 'P', // hours is not changed. // else if 0 == hours // boundary morning hour // hours = hours + 12;// AMPM = 'A';// else// (hours < 12)// AMPM is set to 'A';// hours is unchangedvoid output( int hours, int minutes, char AMPM ); //Precondition:// 0 < hours <=12, 0 <= minutes < 60,// AMPM == 'P' or AMPM == 'A'//Postconditions:// time is written in the format// HH:MM AM or HH:MM PMint main(){int hours, minutes;char AMPM, ans;do{input( hours, minutes );convert ( hours, AMPM );output( hours, minutes, AMPM );cout << "Enter Y or y to continue,"<< " anything else quits."<< endl;cin >> ans;} while ( 'Y'== ans || 'y' == ans );return 0;}void input( int& hours24, int& minutes){char colon;cout << "Enter 24 hour time in the format HH:MM "<< endl;cin >> hours24 >> colon >> minutes;}//Precondition: 0 <= hours < 24,//Postcondition:// if hours >= 12,// hours is replaced by hours - 12,// AMPM is set to 'P'// else // (hours < 12)// hours is unchanged and AMPM is set to 'A'void convert( int& hours, char& AMPM ){if (hours > 12) // definitely in the afternoon{hours = hours - 12;AMPM = 'P';}else if (12 == hours) // boundary afternoon hour AMPM = 'P'; // but hours is not changed.else if (0 == hours) // boundary morning hour{hours = hours + 12;AMPM = 'A';}else // (hours < 12) // definitely morning hour AMPM = 'A'; // hours is unchanged}void output( int hours, int minutes, char AMPM ) {cout << "Time in 12 hour format: " << endl<< hours << ":" << minutes << " "<< AMPM << 'M' << endl;}A typical run follows:20:33:03:~/AW$ a.outEnter 24 hour time in the format HH:MM0:30Time in 12 hour format:12:30 AMEnter Y or y to continue, anything else quits.yEnter 24 hour time in the format HH:MM2:15Time in 12 hour format:2:15 AMEnter Y or y to continue, anything else quits.yEnter 24 hour time in the format HH:MMEnter 24 hour time in the format HH:MM11:30Time in 12 hour format:11:30 AMEnter Y or y to continue, anything else quits.yEnter 24 hour time in the format HH:MM12:30Time in 12 hour format:12:30 PMEnter Y or y to continue, anything else quits.yEnter 24 hour time in the format HH:MM23:59Time in 12 hour format:11:59 PMEnter Y or y to continue, anything else quits.n20:33:59:~/AW$2. Time// Waiting time// Problem 2, Savitch, Programming and Problem Solving with C++ 5th //// file ch5.2.cpp// Program input: current time and a waiting time// each time is number of hours and a number of minutes.// Program output is is the time the waiting period completes.// Use 24 hour time. Allow user repeat.// Notes: The 24 hour boundary, i.e., when the time wraps to the// next day is important here.//// Known Bugs: If the completion time would be in a day later// than the next day after the start, this program gives incorrect // results.//#include <iostream>void input( int& hours24, int& minutes){using std::cout;using std::cin;using std::endl;char colon;cout << "Enter 24 hour time in the format HH:MM "<< endl;cin >> hours24 >> colon >> minutes;}void output( int hours, int minutes){using std::cout;using std::cin;using std::endl;cout << "Time in 24 hour format:\n"<< hours << ":" << minutes << endl;}int main(){using std::cout;using std::cin;using std::endl;int timeHours, timeMinutes, waitHours, waitMinutes,finishHours, finishMinutes;cout << "Compute completion time from current time and waiting period\n";char ans = 'y';while ('y' == ans || 'Y' == ans){cout << "Current time:\n";input(timeHours, timeMinutes);cout << "Waiting time:\n";input(waitHours, waitMinutes);finishHours = timeHours + waitHours;finishMinutes = timeMinutes + waitMinutes;finishHours += finishMinutes / 60;if(finishHours >= 24){finishHours %= 24;cout << "Completion time is in the day following the start time\n";}finishMinutes%= 60;cout << "Completion ";output(finishHours, finishMinutes);cout << "\n\nEnter Y or y to continue, any other halts\n\n";cin >> ans;}return 0;}/*Typical runCompute completion time from current time and waiting period Current time:Enter 24 hour time in the format HH:MM12:30Waiting time:Enter 24 hour time in the format HH:MM15:40Completion time is in the day following the start timeCompletion Time in 24 hour format:4:10Enter Y or y to continue, any other haltsyCurrent time:Enter 24 hour time in the format HH:MM8:30Waiting time:Enter 24 hour time in the format HH:MM15:10Completion Time in 24 hour format:23:40Enter Y or y to continue, any other haltsnPress any key to continue*/3. Project 3 Modify project 2 to use 12 hour time.We provide suggestions on how to proceed in solving this problem.This problem is different from #2 only in the details of managing 12 hour time. The wait time interval could be any number of hours and minutes, so the output should provide the number of days that elapse from the start time until completion.You may want an input routine that verifies that you have entered legitimate 12 hour time data, i.e. hours betwee 1 and 12, minutes between 0 and 59, and includes either an A for AM or a P for PM.Write code to convert the 12 hour start time to 24 hour time and use the code from #3 to computer the finish time.Decide on how to handle finish times that fall in some later day, then convert 24 hour time to 12 hour time and output that using code from #2.4. StatisticsCompute average and standard deviation of 4 entries.General remarks are in the code file which I present here:// file #include <iostream>using namespace std;/*Task: Write a function that computes average (I will callthis the arithmetic mean or simply the mean) and standard deviation of four scores. The average or mean, avg, is computed asavg = ( s1 + s2 + s3 + s4 ) / 4The standard deviation is computed asstd_deviation = ()()() s a s a s a1234-+-+-where a = avg. Note that some statisticians may wish to use 3 instead of 4. We will use 4.Input: scores s1 s2 s3 s4Output: standard deviation and mean.Required: The function is to have 6 parameters. This function calls two others that compute the mean and the std deviation.A driver with a loop should be written to test the functionat the user's option.*///function declaration (or prototype)//When used, the math library must be linked to the//executable.#include <cmath> // for sqrtusing namespace std;void average (double s1, double s2, double s3,double s4, double& avg){avg = ( s1 + s2 + s3 + s4 ) / 4;}// Preconditions: average function must have been called on//the data, and the value of the average passed into the//parameter a//Postconditions: Standard deviation is passed back in//the variable stdDevvoid sD (double s1, double s2, double s3, double s4,double a, double& stdDev){stdDev = sqrt( (s1 - a)*(s1 - a) + (s2 - a)*(s2 - a)+ (s3 - a)*(s3 - a) + (s4 - a)*(s4 - a) )/4 ; }void statistics( double s1, double s2, double s3, double s4, double& avg, double& stdDev );//Preconditions: this function is called with any set of//values. Very large or very small numbers are subject to//errors in the calculation. Analysis of this sort of error //is beyond the scope of this chapter.//PostConditions: avg is set to the mean of s1, s2, s3, s4//and stdDev is set to the standard deviation of s1..s4//function definition:void statistics( double s1, double s2, double s3, double s4, double& avg, double& stdDev ) {average ( s1, s2, s3, s4, avg );sD ( s1, s2, s3, s4, avg, stdDev );}int main(){double s1, s2, s3, s4, avg, stdDev;char ans;do{cout << "Enter 4 decimal numbers, "<< "I will give you the mean "<< endl<< "and standard deviation of the data " << endl;cin >> s1 >> s2 >> s3 >> s4;statistics( s1, s2, s3, s4, avg, stdDev);cout << "mean of " << s1 << " " << s2 << " " << s3<< " " << s4 << " is " << avg << endl<< "the standard deviation of "<< "these numbers is " << stdDev << endl;cout << "y or Y continues, any other terminates" << endl; cin >> ans;} while ( 'Y' == ans || 'y' == ans );return 0;}A typical run follows:21:44:35:~/AW$ a.outEnter 4 decimal numbers, I will give you the meanand standard deviation of the data12.3 13.4 10.5 9.0mean of 12.3 13.4 10.5 9 is 11.3the standard deviation of these numbers is 0.841873y or Y continues, any other terminatesyEnter 4 decimal numbers, I will give you the meanand standard deviation of the data1 2 3 4mean of 1 2 3 4 is 2.5the standard deviation of these numbers is 0.559017y or Y continues, any other terminatesn21:45:05:~/AW$5. Change maker problem.Only notes on the solution are provided for this problem. In my discussion of this problem, I include a word or two on algorithm development, concluding (sometimes only the following).A greedy algorithm works for this problem. A greedy algorithm makes locally optimal choices at each point in the sequence of points in the solution, in the hope that the locally optimal choices will result in a globally optimal solution. This works surprisingly often, including this problem. It is interesting to me that the greedy algorithm fails for some national coinage.I suggest that the student write code to choose the largest number of coins of the largest denomination from the list of coin not yet used. Repeat this on the remaining amount of money for decreasing denominations until no more coins are left.6. Conversion 1Conversion of feet/inches to meters://File: //Task: Convert feet/inches to meters//Input:a length in feet and inches, with possible decimal//part of inches//Output: a length in meters, with 2 decimal places, which//are the 'centimeters' specified in the problem.//Required: functions for input, computation, and output.//Include a loop to repeat the calculation at the user's//option.Remarks: The computation is a simple conversion from //feet + inches to feet with a decimal part, then to meters. //Output is restricted to 2 decimal places.////By 'meters and centimeters' the author means that the//output is to be meters with two decimal places - which is//meters and centimeters. I mention this because my students //always stumble at this because of a lack of knowledge of //the metric system.#include <iostream>using namespace std;void input ( int& feet, double& inches );//Precondition: function is called//Postcondition://Prompt given to the user for input in the format FF II,//where FF is integer number of feet and II is a double//number of inches. feet and inches are returned as entered //by the user.void convert (int feet, double inches, double& meters );//Preconditions://REQUIRED CONSTANTS: INCHES_PER_FOOT, METERS_PER_FOOT//inches < 12, feet within range of values for int type//Postconditions://meters assigned 0.3048 * (feet + inches/12)//observe that the centimeter requirement is met by//the value of the first two decimal places of the converted //feet, inches input.void output( int feet, double inches, double meters );//input: the formal argument for meters fits into a double//output://"the value of feet, inches" <feet, inches>//" converted to meters, centimeters is " <meters>//where meters is displayed as a number with two decimal//placesint main(){int feet;double inches, meters;char ans;do{input ( feet, inches );convert ( feet, inches, meters );output ( feet, inches, meters );cout << "Y or y continues, any other character quits "<< endl;cin >> ans;} while ( 'Y' == ans || 'y' == ans );return 0;}void input ( int& feet, double& inches ){cout << "Enter feet as an integer: " << flush;cin >> feet;cout << "Enter inches as a double: " << flush;cin >> inches;}const double METERS_PER_FOOT = 0.3048;const double INCHES_PER_FOOT = 12.0;void convert (int feet, double inches, double& meters ){meters = METERS_PER_FOOT * (feet +inches/INCHES_PER_FOOT);}void output( int feet, double inches, double meters ) {//inches, meters displayed as a number with two decimal //placescout.setf( ios::showpoint );cout.setf( ios::fixed );cout.precision(2);cout << "the value of feet, inches" << feet << ","<< inches << endl<< " converted to meters, centimeters is "<< meters << endl;}/*A typical run follows:06:59:16:~/AW$ a.outEnter feet as an integer: 5Enter inches as a double: 7the value of feet, inches5,7.00converted to meters, centimeters is 1.70Y or y continues, any other character quitsyEnter feet as an integer: 245Enter inches as a double: 0the value of feet, inches245,0.00converted to meters, centimeters is 74.68Y or y continues, any other character quitsq06:59:49:~/AW$*/7. Conversion 2Conversion of meters back to centimeters.//file: //Task: Convert meters with centimeters (just the decimal//part of meters)to feet/inches////Input: a length in feet and inches, with possible decimal //part of inches//Output: A length measured in feet with any decimal fraction //converted to inches by multiplying by 12. Fractions of an//inch are represented by 2 decimal places.////Required: functions for input, computation, and output.//Include a loop to repeat the calculation at the user's//option.////Remark: The computation is a simple conversion from meters //to feet, inches, where inches has a decimal part.//Output is restricted to 2 decimal places//Comment: Please see Problem 4 for discussion of 'meters and //centimeters'#include <iostream>using namespace std;void input ( double & meters );//Precondition: function is called//Postcondition://Prompt given to the user for input of a number of meters as //a double. input of a double for meters has been acceptedvoid convert (int& feet, double& inches, double meters );//Preconditions:// REQUIRED CONSTANTS: INCHES_PER_FOOT, METERS_PER_FOOT//Postconditions://feet is assigned the integer part of meters (after//conversion to feet units) inches is assigned the//fractional part of feet ( after conversion to inch unitsvoid output( int feet, double inches, double meters );//input: the formal argument for meters fits into a double//output://"the value of meters, centimeters is: " <meters>//" converted to English measure is "//<feet> "feet, " <inches> " inches "//where meters is displayed as a number with two decimal//placesint main(){int feet;double inches, meters;char ans;do{input ( meters );convert ( feet, inches, meters );output ( feet, inches, meters );cout << "Y or y continues, any other character quits "<< endl;cin >> ans;} while ( 'Y' == ans || 'y' == ans );return 0;}void input ( double& meters ){cout << "Enter a number of meters as a double \n";cin >> meters;}const double METERS_PER_FOOT = 0.3048;const double INCHES_PER_FOOT = 12.0;void convert (int &feet, double& inches, double meters ){double dfeet;dfeet = meters / METERS_PER_FOOT;feet = int( dfeet );inches = (dfeet - feet)*INCHES_PER_FOOT;}void output( int feet, double inches, double meters ){//meters is displayed as a double with two decimal places //feet is displayed as int, inches as double with two//decimal placescout.setf( ios::showpoint );cout.setf( ios::fixed );cout.precision(2);cout << "The value of meters, centimeters " << endl<< meters << " meters" << endl<< "converted to English measure is " << endl << feet << " feet, " << inches << " inches"<< endl;}/*A typical run follows:07:56:28:~/AW$ a.outEnter a number of meters as a double6.0The value of meters, centimeters6.00 metersconverted to English measure is19 feet, 8.22 inchesY or y continues, any other character quitsyEnter a number of meters as a double75The value of meters, centimeters75.00 metersconverted to English measure is246 feet, 0.76 inchesY or y continues, any other character quitsq07:56:40:~/AW$*/8. Conversion 3This exercise combines the two previous exercises. Convert between feet/inches and meters. The direction is the user's option.// file: //Task: Convert between meters and feet/inches at user's//option Within conversion, allow repeated calculation//after end of either conversion, allow choice of another //conversion.//Input: At program request, user selects direction of//conversion. Input is either feet/inches(with decimal//fraction for inches) OR meters with 2 place decimal//fraction that represents the centimeters.//Output: Depends on user selection: either meters or//feet and inches.//Method: Suggested by problem statement: use if-else//selection based on the user input to choose between//functions written for problems 4 and 5 above.//Required: functions for input, computation, and output. //Include a loop to repeat the calculation at the user's //option.#include <iostream>using namespace std;void inputM ( double& meters );//Precondition: function is called//Postcondition://Prompt given to the user for input of a number of meters //as a doublevoid inputE ( int& feet, double& inches );//Precondition: function is called//Postcondition://Prompt given to the user for input in the format FF II,//where FF is an int number of feet and II is a double number //of inches feet and inches are returned as entered by the//user.void convertEtoM (int feet, double inches,double& meters );//Preconditions://REQUIRED CONSTANTS: INCHES_PER_FOOT, METERS_PER_FOOT//inches < 12, feet within range of values for an int//Postconditions://meters assigned 0.3048 * (feet + inches/12)//Observe that the requirement to produce centimeters is met //by the value of the first two decimal places of meters.void convertMtoE (int& feet, double& inches,double meters );//Preconditions:// REQUIRED CONSTANTS: INCHES_PER_FOOT, METERS_PER_FOOT//Postconditions://the variable feet is assigned the integer part of//meters/METERS_PER_FOOT//the variable inches is assigned the fractional part of//feet after conversion to inch units.void output( int feet, double inches, double meters );//input: the formal argument for meters fits into a double//output://"the value of feet, inches" <feet, inches>//" corresponds to meters, centimeters is " <meters>//where meters is displayed as a number with two decimal//placesvoid EnglishToMetric ();// requests English measure, converts to metric, outputs bothvoid MetricToEnglish();// request metric measure, converts to English, outputs bothint main(){char ans;do{int which;cout << "Enter 1 for English to Metric or " << endl<< "Enter 2 for Metric to English conversion"<< endl;cin >> which;if ( 1 == which )EnglishToMetric();elseMetricToEnglish();cout << "Y or y allows another choice of conversion. "<< "any other quits" << endl;cin >> ans;} while ( 'y' == ans || 'Y' == ans );return 0;}void MetricToEnglish(){int feet;double inches, meters;char ans;do{inputM ( meters );convertMtoE ( feet, inches, meters );output ( feet, inches, meters );cout << "Y or y continues, any other character quits "<< endl;cin >> ans;} while ( 'Y' == ans || 'y' == ans );}void EnglishToMetric (){int feet;double inches, meters;char ans;do{inputE ( feet, inches );convertEtoM ( feet, inches, meters );output ( feet, inches, meters );cout << "Y or y continues, any other character quits "<< endl;cin >> ans;} while ( 'Y' == ans || 'y' == ans );}void inputE ( int& feet, double& inches ){cout << "Enter feet as an integer: " << flush;cin >> feet;cout << "Enter inches as a double: " << flush;cin >> inches;}void inputM ( double& meters ){cout << "Enter a number of meters as a double " << endl;cin >> meters;}const double METERS_PER_FOOT = 0.3048;const double INCHES_PER_FOOT = 12.0;// convert English measure to Metricvoid convertEtoM (int feet, double inches, double& meters ) {meters = METERS_PER_FOOT * (feet +inches/INCHES_PER_FOOT);}// convert Metric to English measurevoid convertMtoE (int &feet, double& inches,double meters ){double dfeet;dfeet = meters / METERS_PER_FOOT;feet = int( dfeet );inches = (dfeet - feet)*INCHES_PER_FOOT;}void output( int feet, double inches, double meters ){// meters is displayed as a double with two decimal// places// feet is displayed as int, inches as double with two //decimal placescout.setf( ios::showpoint );cout.setf( ios::fixed );cout.precision(2);cout << meters << " meters "<< "corresponds to "<< feet << " feet, " << inches << " inches"<< endl;}/*A typical run follows08:59:38:~/AW$ a.outEnter 1 for English to Metric orEnter 2 for Metric to English conversion2Enter a number of meters as a double7575.00 meters corresponds to 246 feet, 0.76 inchesY or y continues, any other character quitsnY or y allows another choice of conversion. any other quits yEnter 1 for English to Metric orEnter 2 for Metric to English conversion1Enter feet as an integer: 246Enter inches as a double: 0.7675.00 meters corresponds to 246 feet, 0.76 inchesY or y continues, any other character quitsqY or y allows another choice of conversion. any other quitsq09:00:08:~/AW$*/9-12. More Conversions—No Solutions Provided.These problems differ from problems whose solutions have already been presented only in the names and specific factors used to carry out the conversions.13. The Area of an Arbitrary TriangleI provide only notes for this problem.To determine the area of an arbitrary triangle can be computed using Hero’s formula for the area of a triangle1 the lengths of the edges of which are a, b, and c:s = (a + b + c)/2area = sqrt(s(s - a)(s - b)(s - c))It is necessary to test whether edges of lengths a, b and c actually form a triangle. The test for values of a, b and c to form a triangle is that each of the following inequalities be satisfied.a +b > c1 Hero, Heron, or Hron, was a mathematician conjectured to have lived between the 3rd and 2nd centuries BCE. He lived in Alexandria, but wrote in Greek. This formula is ascribed to him as is Hero’s engine, where steam recoil rotates a sphere or wheel.。
《C语言程序设计(第2版)》课后习题参考答案prt
![《C语言程序设计(第2版)》课后习题参考答案prt](https://img.taocdn.com/s3/m/26f919e5ab00b52acfc789eb172ded630b1c9808.png)
《C语言程序设计》(邱晓红主编)课后习题参考答案第1章C语言及程序设计概述1.单选题(1)A (2)B (3)A (4)B (5)C2.填空题(1)//,/*…*/(2)scanf()(3)printf()3.判断题(1)对(2)错(3)错(4)对1.4简答题①概述C语言和C语言程序的主要特点。
答:1.C语言是高级语言。
它把高级语言的基本结构和语句与低级语言的实用性结合起来。
2。
C语言是结构式语言。
结构式语言的显著特点是代码及数据的分隔化,即程序的各个部分除了必要的信息交流外彼此独立。
这种结构化方式可使程序层次清晰,便于使用、维护以及调试。
①C语言功能齐全。
具有各种各样的数据类型,并引入了指针概念,可使程序效率更高。
②C语言适用范围大。
适合于多种操作系统,如Windows、DOS、UNIX、LINUX等等;也适用于多种机型。
②请编程,在计算机屏幕上显示:“您好,欢迎进入C语言世界!”解:#include<stdio.h>void main(){printf("您好,欢迎进入c预言世界!");}第二章:数据类型运算符与表达式1.单选题(1)C (2)D (3)C (4)B (5)C (6)A (7)B (8)D (9)A (10)B(11)C (12)C (13)D (14)A (15)B (16)C (17)A (18)A (19)B (20)C (21)C (22)D (23)C (24)A (25)D (26)B (27)C (28)B (29)B (30)A 2.填空题(1)sqrt(pow(y,x)+log10(y)) (2)36(3)6 (4)3 3(5)6 (6)36(7)int x=8,y=8; (8)1(9)E (10)7,9,6,8)(11)6 (12)66,96(13)240 (14)1,1,-1,-1(15)5,2,6 (16)1(17)!(18)2(19)(a>0&&a<101)&&(a%3==0||a%7==0)(20)A3.程序分析题(1)2 7 (VC++环境下,其它编译环境可能有不一样的结果)2 74 94 412 12(2)3 1 4 01 -616(3)100 d 68 D97 a 49 1(4)0 1 0 1(5)2 4 6 7-0.5800000 7.00000046.5800007.500000(6)33 12 113 13 082 32(7)618 30181(8)1 1 0 04.改错题(1)①无初始赋值,不能输出②数据精度丢失③少“;”号④单字符变量不能保存字符串常量⑤不能连续初始化⑥非法标识符(2)short i=38000溢出PI=3.1416 常量不能修改值Printf(“%d”,x%y) %必须是整数a*=(b+c)/=d复合赋值左边不能是表达式5、(1)#include <stdio.h>int main(){int H;float v,L1,L2,L,T,s1,M;printf("请输入开始里程数,单位为千米:\n");scanf("%f",&L1);printf("请输入结束里程数,单位为千米:\n");scanf("%f",&L2);printf("请输入时间,格式为时,分,秒\n");scanf("%d,%f,%f",&H,&M,&s1);T=H+M/60.0+s1/3600.0;//将时间折算成小时;L=L2-L1;//计算出这段时间走的路程,以千米计;v=L/T;printf("%f\n",v);return 0;}(2)#include <stdio.h>#define PI 3.14int main(){double r=2.5,h=5,V;V=(PI*r*r*h)/3;printf("%f\n",V);return 0;}第三章:算法概念与顺序结构程序设计1.选择题(1)D (2)D (3)D (4)B (5)C (6)A (在16位机答案为D)(7)B (8)C (9)B (10)D2.填空题.(1)一条语句;(2)小于左右(3)%%(4)输出项列表输出控制符(5)取地址取a的地址(6)从盘获取一个字符(7)大括号(8)f=68.000000(9)n1=%d\n n2=%d(10)7,5,c=33.程序分析题.(1)i=100,c=a,f=1.234000(2)i=65535,j=65536(10)1234,123.5,12345.53.4 编程题①编写一个程序,交换两个数的值。
c语言第五章选择结构程序设计(习题册答案)
![c语言第五章选择结构程序设计(习题册答案)](https://img.taocdn.com/s3/m/94f8ce08ae45b307e87101f69e3143323968f5eb.png)
c语言第五章选择结构程序设计(习题册答案)第五章选择结构程序设计基础练习(A)一、填空题1、关系表达式的运算结果是逻辑值。
C语言没有逻辑型数据,以1代表“真”,以0代表“假”。
2、逻辑运算符!是单目运算符,其结合性是由右结合性。
3、C语言提供的三种逻辑运算符是&&、|| 、!。
其中优先级最高的为!,优先级最低的为| | 。
4、逻辑运算符两侧的运算对象不但可以是0和1,或者是0和非0的整数,也可以是任何类型的数据。
系统最终以0 和非0 来判定它们属于“真”或“假”。
5、设y为int型变量,请写出描述“y是偶数”的表达式(y%2==0)。
6、设x,y,z均为int型变量,请写出描述“x或y中有一个小于z”的表达式x<z||y<="">7、条件“2<x<3或x<-10”的c语言表达式是x<-10||x>2&&x<3。
</x<3或x<-10”的c语言表达式是x<-10||x>8、判断char型变量ch是否为大写字母的正确表达式是(ch>=‘A’)&&(ch<=‘Z’)。
9、当a=3,b=2,c=1时,表达式f=a>b>c的值是0。
10、当a=5,b=4,c=2时,表达式a>b!=c的值是1。
11、已知A=,B=2,C=,表达式A>B&&C>A||A<b&&!c>B的值是0。
</b&&!c>12、若a=6,b=4,c=2,则表达式!(a-b)+c-1&&b+c/2的值是1。
13、有int x,y,z;且x=3,y=-4,z=5,则表达式(x&&y)==(x||z)的值为1。
14、有int x,y,z;且x=3,y=-4,z=5,则以下表达式的值为1。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
循环结构程序设计P115 5.1 用while计算1至100的合.#include<stdio.h>int main(){int i=1,sum=0;while(i<=100) //对于需要运算的值,要么在运算前可以赋值,要么一开始要指定.{sum=sum+i;i++;}printf("The sum is %d .\n",sum);return 0;}P117 5.2 用do-while来做1至100的合.#include<stdio.h>int main(){int i=1,sum=0;do// do-while可以做的事,用while都可以做到.{ //do-while先做一次执行,再判断条件,而while却是先做一个条件,再执行.sum=sum+i;i++;}while(i<=100);printf("The sum is %d .\n",sum);return 0;}P118 5.3 比较do-while与while的差别.#include<stdio.h>{int i,sum=0;printf("Please input a number :");scanf("%d",&i); //输入10以内,正常,11的话,则sum仍然是0.while(i<=10){sum=sum+i;i++;}printf("The sum of 1-10 is %d .\n",sum);return 0;}#include<stdio.h>int main(){int i,sum=0;printf("Please input a number :");scanf("%d",&i); //输入10以内,结果一样.输入11的话,先做操作,所以sum=11.do{sum=sum+i;i++;}while(i<=10); //此重点在于理解二者的差别.printf("The sum of 1-10 is %d .\n",sum);return 0;}P126 5.4 break的例子.#include<stdio.h>int main(){int i,b=0,a,c;for(i=0;i<=1000;i++){printf("Please input amount :"); //循环体内套有输出语句以及跳出语句.scanf("%d",&a);b=b+a;if(b>=100)break; //break是用于跳出循环,对if无效,对while for switch 这一类.}}c=b/i;printf("conut is %d , aver is %d ",i+1,c); //注意%号后的形式,否则可能输出错误.return 0;}P127 5.5 continue的例子.#include<stdio.h>int main(){int i;for(i=1;i<20;i++){if(i%3!=0){continue; //跳过本次I,执行下一个i.}printf("%d ",i);}printf("\n");return 0;}P128 5.6 形成一个4*5的矩阵.#include<stdio.h>int main(){int i,j,a=0; //没有给初值,会出现警告: 使用了未初始化的局部变量“a”.for(i=1;i<=4;i++){for(j=1;j<=5;j++,a++) // a用来控制换行.{if(a%5==0){printf("\n");}printf("%d\t",i*j);}}printf("\n");return 0;}P131 5.7 用一个交错的式子求哌的近似值.#include<stdio.h>#include<math.h>int main() //四分之哌等于(1)-(1/3)+(1/5)-(1/7)+(1/9)-(1/11).{float s=1,n=1,m,sum=0,t;for(m=1;;m=m+2) //不确定哪项才会小于等于十的负六次方,所以不指定,无限下去.{ //不指定第二项,执行语句中应该有控制跳出的句子,否则死循环.t=(s)*(n/m); //这是第一项,s是符号,if(fabs(t)<=1e-6) //应该写在这里,题目要求这一项不累加进去.{break;}sum=sum+t; //因为累加项在这里,所以,一旦跳出就不会累加进来了.s=s*(-1); //变号一次.}printf("四分之一哌的值是%f.\n",sum);printf("一个完整哌的值是%f.\n",sum*4);return 0;}//下面这段小代码用来验证关于数值型数据类型的关系.去掉注释,可运行.//如果出现类似值为全1或是全零的话,一般可以考虑数据类型赋值或是定义错了的问题.//#include <stdio.h> //这是关于int float double三者关复杂关系的,乱啊,如果看不懂,可以通过实验自己明白来.////int main() //在C语言中,1.0认为是实数,即是double型,所以,如果你把它用float输出的话,会有警告:警告 1 warning C4305: “=”: 从“double”到“float”截断.//{// float m,a,b,c; //一旦定义了是这种类型的话,输出或是赋值的时候只能扩展不能截断,意思就是能变成double型,不能变成int型啦.而且后面的赋值会跟着它变成相应的类型.比如下面的m=1,其实得到的是m=1.0.// int d,e,f;// m=1;// a=1.0/3;// b=1/3;// c=m/3;// d=1.0;// e=1/4;// f=1.0/4;// printf("%lf(float用double的%lf来输出是可以的.)\n%f\n%f\n%f\n",m,a,b,c); //不管上面定义什么,这边写的输出类型是什么,就按相应的类型输出,有可能会出错,所以建议按定义的类型来输出.当然扩展的是不会错的,截断的是会错的,比如float可以用%lf来输出,而不能用%d来输出.// printf("%d\n%d\n%d\n",d,e,f); //但是,不相应的int型不可以用%f来输出的.因为int float就不同种类,一个是整数,一个是小数,float double同样是有小数点的!!!!// return 0;//}#include<stdio.h>int main() //这个就是著名的Fibonacci(费波那契数列问题){int f1=1,f2=1,f3,i;printf("%12d\n%12d\n",f1,f2);for(i=1;i<=38;i++) //注意,这是个基础问题,(i=1;i<=5;i++)这里其实进行了次运算,因为有f1,f2,要求有个,所以要有个.要么写<=38,要么写<39,边界问题一定要注意,不可以太随意!!!!{f3=f1+f2;printf("%12d\n",f3); //这个问题同样适用于"一对兔子一个月生一对"的问题.,f1=f2; //f1=f1+f2;此时它们各是,所以,现在的f1是.f2=f3; //f2=f2+f1;此时的f1已经是最先二者之和了.可以不用到f3.}return 0;}#include<stdio.h>#include<math.h>int main(){double num;int i;printf("Please input a number :");scanf("%lf",&num); //因为sqrt要求是浮点型,那就给它浮点型,需要时再强制转换.for(i=2;i<=sqrt(num);i++) //这边是<=号没错.{if((int)num%i==0) //如果在这期间有任何一个可以为零的话,则不是素数.{break; //当然跳出.}} //执行到这里的时候,i=5,已经变成了!!if(i<=sqrt(num)){printf("Not %d",(int)num);}else//如上所述,i=5,超出了求根的值,所以是素数.{printf("Yes %d",(int)num);}return 0;}P137 5.10 求100至200间的素数.#include<stdio.h>//不解释,HOHO>>>>...#include<math.h>int main(){double j;int i,k=0;for(j=100;j<=200;j++){for(i=2;i<=sqrt(j);i++){if((int)j%i==0){break;}}k=k+1; //这里是布局的开头.学习一下,有助逻辑.if(i<=sqrt(j)){printf("Not %d ",(int)j);if(k%5==0) //5个换一次行.{printf("\n");}}else{printf("Yes %d ",(int)j);if(k%5==0){printf("\n");}}}return 0;}P139 5.11 密码转换.#include<stdio.h>int main(){char c;c=getchar();while(c!='\n') //这也可以用数组来实现.{if((c>='a'&&c<='z')||(c>='A'&&c<='Z')){if((c>='w'&&c<='z')||(c>='W'&&c<='Z')){c=c-22;}else{c=c+4;}printf("%c",c);c=getchar(); //套在循环里,依次得到字母,而while中判断回车为结束.}}printf("\n"); //这是布局问题.return 0;}P140 0.3 最大公约数和最小公倍数.#include<stdio.h>//最大公约数用累除法,除到无余数时的被除数是最大公约数.main (){int m, n, c, d;int gcd(); //这是最大公约数的缩写,此处调用函数,可以不写里面的实参.int lcm(); //这是最小公倍数的缩写,此处调用函数,可以不写里面的实参.printf("Please input two number :\n");scanf("%d %d",&m,&n);c=gcd(m,n); //c获取最大公约数d=lcm(m,n); //d获取最小公倍数printf("The GCD of %d and %d is : %d !\n", m, n, c);printf("The LCM of %d and %d is : %d !\n", m, n, d);return 0;}int gcd(int x, int y) //最大公约数Greatest Common Divisor{int temp;while(x%y!=0){temp=y; //y在下一轮中作为除数,即是下一轮中的X,所以先闪一边去.y=x%y; //x,y的余数作为下一轮中的Y,由x%y来取得.x=temp; //刚才temp中存储了y的值,现在拿出来作为下一轮中的X使用.}return y; //这是每一轮中的被除数,按原理来,这就是最大公约数,即累除法的原理. }int lcm(int x, int y) //最小公倍数Lowest Common Multiple{int i, temp;if(x<y) //此段代码结果是保证二者大的数在X上,小的数在Y上.即小于号降序.{ //以下为经典三行码,实现两个数的互换.temp=x;x=y;y=temp;}for(i=1; i<=y; i++) //设定一个区间,从1至大的数之间的循环.{if(!((x*i)%y)) //此式子如有余数,加上"!"号,会是假,则不返回,进行下一轮.{ //如此往复,直到取模无余数,那么小的数X乘以区间当前的I值,就是最小公倍数.return x*i;}}}P140 0.4 判断一串输入的字符.#include<stdio.h>int main(){char ch;int a=0,b=0,c=0,d=0,e=0;printf("Please input the string\n");while((ch=getchar())!='\n') //直到回车.{if(ch<='z'&&ch>='a'){a++;}else if(ch==' '){c++;}else if(ch<58&&ch>47){d++;}else if(ch<='Z'&&ch>='A'){b++;}else{e++;}}printf("大写%d 小写%d 空格%d 数字%d 其它%d\n",a,b,c,d,e);}#include<stdio.h>//不理解时可以百度或是谷歌更多的信息.int main() //想办法既快速做完,又要消化理解!!!{int temp,i,a,n,sum=0; //主逻辑,友好性暂时放松.scanf("%d %d",&a,&n); //a是数字,n是要乘的个数.temp=a; //先把第一阶的值存起来.for(i=0;i<n;i++){sum=sum+a;printf("%d + ",a); //事关布局.a=a*10+temp; //重点是每次乘,然后加上上一个数.}printf("= %d .",sum);return 0;}P140 0.6 1!+2!+3!+4!.....的值. #include<stdio.h>int main() //1!+2!+3!+4!.....{int i,j,k,sum=0,m=1;scanf("%d",&k); //比如设定为,值为.for(i=1;i<=k;i++) //第一层循环,指定到.{for(j=1;j<=i;j++) //第二层循环,指定至当前数.{m=m*j;} //到此是阶乘的结构.sum=sum+m;m=1;}printf("%d",sum); //完全不理解时,搜索并参考.return 0; //尝试自己做,第一次做出来就是自己的东西了. }#include<stdio.h>int main(){int a,b;double c,asum=0,bsum=0,csum=0;for(a=1;a<=100;a++) //三个块分别注释验证结果.{asum=asum+a;}for(b=1;b<=50;b++) //在VS运行中,注意*.cpp为C++语言.{bsum=bsum+b*b; //为了避免语言差别,请注意文件名为*.c.}for(c=1;c<=10;c++) //c作浮点运算,所以定义在double类型中.{csum=csum+1/c;}printf("%lf",asum+bsum+csum);return 0;}PP#include<stdio.h>#include<math.h>int main(){int j,k,s[6],x=100,y,sum=0;for(j=153;j<=154;j++){for(k=2;k>=0;k--){s[k]=j%(int)pow(10,k+1)/(int)pow(10,k);y=pow(s[k],3);sum+=y;printf("%d-%d--%d\t",k,s[k],j);}printf("%d\n",sum);}return 0;}P140 0.8 水仙花数.//#include <stdio.h> //一步步的发现问题.////int main() //在%和/号之间,以前pow.以后再做.//{// int i,j,k,a,b,c,sum=0; //这里逻辑对,算出来却错了.// for(i=2;i<=4;i++) //计算机在想什么,看来它的大脑难以模拟.// {// for(j=pow(10,i);j<=pow(10,i+1)-1;j++) //我不完全明白它遵守的逻辑. // {// for(k=0;k<=i;k++)// {// sum+=pow((j%pow(10,i+1)/pow(10,i)),3);// }// if(sum==j)// {// printf("%d 是水仙花数!\n",j);// }// sum=0;// }// }// return 0;//} //为什么还是无法实现?!#include<stdio.h>#include<math.h>int main(){int a,b,c,i,sum=0; //这里只计算三位数的.for(i=100;i<1000;i++){a=i/100;b=i%100/10;c=i%10;sum+=a*a*a+b*b*b+c*c*c;if(sum==i){printf("%d 是水仙花数.\n",i);}sum=0;}return 0;}P141 0.9 完数.#include<stdio.h>int main(){int i,j,r;for(i=1;i<=1000;i++) //零是个临界值,不能包括它.{r=0; //每次清零重来.类似水仙中的sum.for(j=1;j<i;j++){if(i%j==0) //除得尽即是因子.{r=r+j; //然后累加进去.}}if(r==i) //若相等.{printf("%d 是完数.\n",i);}}return 0;}P141 0.10 2/1+3/2+5/3+8/5+13/8…#include<stdio.h>int main() //10.007051{double i,a=2,b=1,c,s=0; //a是分子,b是分母.for(i=0;i<6;i++) //二十可以用户指定.{s+=a/b; //中间储值变量.c=a+b;b=a;a=c;}printf("%lf\n",s);return 0;}#include<stdio.h>int main() //从一百开始,减一半再自加两次,下降一次,反弹一次.{double sum=100,high=100,up,donw,i;for(i=1;i<10;i++) //不管指定到哪个数,都不会超过三百.{up=high/2;donw=up;high=donw; //自咬尾巴问题.sum+=donw*2;}printf("%lf %lf\n",donw,sum);return 0;}P141 0.12 猴子吃桃子.#include<stdio.h>int main() //从一百开始,减一半再自加两次,下降一次,反弹一次.{int i,sum=1;for(i=1;i<=10;i++) //临界要清楚,结果要与手算的前几个实例相匹配.{printf("倒数第%d天还剩有%d个桃子.\n",i,sum);sum=(sum+1)*2;}//printf("%d\n",sum);return 0;}#include<stdio.h>#include<conio.h>main() //只关注左半部分.右半部分无视空格.{int i,j,k,m=6; //m可指定,指定中心点位置.可任意奇偶.for(i=1;i<=m;i++) //上半部分.其实也是正三角.{for(j=1;j<=m-i;j++) //一到中心点前i个位置填充空格.printf(" ");for(k=1;k<2*i;k++) //空格后向前填充星号的个数.是奇数.一,三,五... printf("*");printf("\n");}for(i=m-1;i>0;i--) //下半部分.其实也是倒三角.{ //减一是因为行数问题.这是中心行以下的.for(j=m-1;j>=i;j--)printf(" ");for(k=1;k<2*i;k++)printf("*");printf("\n");}getch(); //用户反应后结束.但,没必要.}。