武夷学院c语言程序期末试卷,高教c语言程序设计(2011版)课后编程题答案(五篇材料)...

/* 从键盘读入学生的信息*/

{

printf("Input student %d:", i+1);

scanf ("%ld%s",&stu[i].num, stu[i].name);

for(j=0,t=0;j<5;j++)

{scanf("%f%*c",&stu[i].score[j]);

t=t+stu[i].score[j];

average[j]+=stu[i].score[j];

}

stu[i].aver=t/5;

}

out.num=0;strcpy(out.name,"5course'ave");

for(j=0;j<5;j++)

out.score[j]=average[j]/SIZE;

fsave( );

/* 调用函数保存学生信息 */

fp = fopenfun ("student.dat", "rb");

printf (" No.

Name

course1 course2 course3 course4 course5\n");

while ( fread(&out, sizeof(out), 1, fp) )

/*读入数据块*/

{printf ("%8ld %-12s", out.num, out.name );

for(j=0;j<5;j++)

printf ("%8.2f", out.score[j]);

printf("\n");

}

fclose(fp); /* 关闭文件 */ } 4. 参考代码如下 #include FILE *fopenfun(char *file,char *model) {

FILE *fp;

if ( ( fp = fopen (file, model) ) == NULL )

{

printf ("Cannot open file of %s.\n",file);

//打开文件出错显示提示信息

exit (0);

//调用exit函数终止程序运行

}

else return fp; } #define SIZE 5 struct warehouse /* 定义结构体*/ {

char KNO[10];

int KNOM }; //主函数 main ( ) {

FILE *fpr,*fpw;

struct warehouse t;

fpr=fopenfun("CK.txt","r");

fpw=fopenfun("XK.txt","w");

while(!feof(fpr))

{

fscanf(fpr,"%s%d",t.KNO,&t.KNOM);

if(t.KNOM>100)

fprintf(fpw,"%s %d\n",t.KNO,t.KNOM);

}

fclose(fpr); /* 关闭文件 */

fclose(fpw); /* 关闭文件 */ }

第九章

1.(1)30 (2)3 (3)9 (4)29 2.(1)1 (2)1 (3)1 (4)7 (5)15 (6)6 3.参考代码如下 #includevoid main() {

char a,b;

a='C';

b=a&0125;

//0125的二进制为01010101

printf("%d\n",b); } 4.参考代码如下 #includevoid main() {int i,bit;

/* 定义循环变量i和位1/0标志变量bit */ unsigned int n,mask;

/* 定义欲转换的整数n和屏蔽字变量mask */ mask=0x80000000;

/* 初始屏蔽字,从左边最高位开始检查 */ printf("Enter a integer of Hexadecimal :"); scanf("%x",&n);

/* 输入要转换的整数 */ printf("binary of %x is:",n); for(i=0;i<32;i++)

/* 循环检查32位,并输出结果 */ { if(i%8==0&&i!=0)printf(","); /* 习惯上二进制每8位用“,”分隔以便查看*/

bit=(n&mask)?1:0;

/* n&mask非0,该位为1;否则该位为:0 */

printf("%1d",bit);

/* 输出1或0 */

mask=mask>>1;

/* 右移1位得到下一个屏蔽字 */

}

printf("\n"); } 5.参考代码如下 #include void main() {

unsigned int value,res;

int n1,n2;

printf("请输入一个整数:\n");

scanf("%u",&value);

printf("输入n

1、n2:\n");

scanf("%d",&n1);

scanf("%d",&n2);

if(n1>=n2||n2>32)

printf("输入有误!\n");

res = ( ( value << (n1-1) ) >> (31-n2+n1) ) << (32-n2);

//先向左移n1-1位,再将结果向右移n1-1+32-n2,再将结果左移32-n2位。

printf("%u\n",res); }

第十章

编程题

1. 参考代码如下: #include #define rem(a,b) (a)%(b) void main() {

int x,y,z;

scanf("%d%d",&x,&y);

z=rem(x,y);

printf("%d\n",z); } 2. 参考代码如下: #include #define cube(x) (x)*(x)*(x) #define judge(x,y) (x)*(y)<50?1:0 void main() {

int x,y,z;

scanf("%d%d",&x,&y);

z=cube(x);

printf("%d,%d\n",z,judge(x,y)); } 3. 参考代码如下: #include #define calc(year) (year)%4==0&&(year)%100!=0||(year)%400==0 #define judge(year) calc(year)?1:0 void main() {

int year;

scanf("%d",&year);

if(judge(year))

printf("%d is leap year!\n",year);

else

printf("%d is not a leap year!\n",year); } 4. 参考代码如下: #include #define judge(a,b,c) a+b>c&&b+c>a&&a+c>b #define s(a,b,c) (a+b+c)/2 #define area(a,b,c) sqrt(s(a,b,c)*(s(a,b,c)-a)*(s(a,b,c)-b)*(s(a,b,c)-c)) void main() {

float a,b,c;

scanf("%f%f%f",&a,&b,&c);

if(judge(a,b,c))

printf("The triangle area is %f!\n",area(a,b,c));

else

printf("It's not a triangle!\n"); }

第十一章

一.单选题

1-5 CBBDD

6 D 二.填空题

1.struct link *next; 2.①struct student * ②tail->next ③head 3.Answer:3 4. ①break ②(struct data *)malloc(struct data) ③while(1) ④p!=NULL ⑤p=p->link 5. ①x ②p ③s

三、编程题

1. 参考代码如下:

#include

#include

#include

#define N 3

typedef struct

{

char no[11];

char name[15];

float score[N];

float sum; } studdatatype; typedef struct z1

{

studdatatype studdata;

struct z1 *next; } STUDENT; /*以下是函数原型*/ STUDENT *create();

void print(STUDENT *head);

main() {

STUDENT *head;

head=create();

print(head);

/*I/O函数*/

/*动态内存分配函数及其他函数说明*/

/*字符串函数*/

/*定义常数*/

/*学生数据类型*/

/*定义结点数据类型*/

/*创建链表*/

/* 显示所有记录*/

/*定义链表头指针*/

} /*创建链表*/ STUDENT *create() {

STUDENT *head,*p,*listp;

char no[11];

head=(STUDENT *)malloc(sizeof(STUDENT));//建立头结点

head->next=NULL;

listp=head; //当前指针指到头结点

printf("输入一个学生信息(学号(* 结束)、姓名,三门课成绩:");

scanf("%s",&no);

while(no[0]!='*')

{

p=(STUDENT *)malloc(sizeof(STUDENT));//建立新结点

strcpy(p->studdata.no,no);

//将输入的数据存储到新结点的数据域

scanf("%s",p->studdata.name); scanf("%f%f%f",&p->studdata.score[0],&p->studdata.score[1],&p->studdata.score[2]) ;

p->studdata.sum=p->studdata.score[0]+p->studdata.score[1]+p->studdata.score[2];

p->next=NULL;

//将新结点的指针域置为空

listp->next=p;

//将新结点连接到当前指针的后面

listp=p;

//将新结点作为当前结点

printf("输入一个学生信息(学号(* 结束)、姓名,三门课成绩:");

scanf("%s",&no);

//输入下一个学生的成绩

}

return head; } /*输出链表中结点信息*/ void print(STUDENT *head) {

int i=0;

/* 统计记录条数*/

STUDENT *p;

/*移动指针*/

system("cls");

/*清屏*/

p=head->next;

/*初值为第一个结点的指针*/

printf("\n\n\n*******************************STUDENT********************\n");

printf("| rec| no

|

name

| sc1| sc2| sc3|

sum |\n");

printf("|----|----------|---------------|----|----|----|--------|\n");

while(p!=NULL)

{

i++;

printf("|%4d|%-10s|%-15s|%4.0f|%4.0f|%4.0f|%8.2f|\n",i,p->studdata.no, p->studdata.name,p->studdata.score[0],p->studdata.score[1],p->studdata.score[2],p->studdata.sum);

p=p->next;

}

printf("********************************end***********************\n"); }

2. 参考代码如下:

/*查找成绩最高的学生信息*/ void searchmaxscore(STUDENT *h) {

STUDENT *p,*pmax;

p=pmax=h->next;

while(p!=NULL) /*当指针不为空时,循环继续*/

{

if(pmax->studdata.sumstuddata.sum)

pmax=p;

p=p->next;

/*移动指针,指向下一结点*/

}

printf("\n\n\nThe highest total score of the students' information :\n");

printf("*******************************STUDENT********************\n");

printf("| no

|

name

| sc1| sc2| sc3|

sum |\n");

printf("|----------|---------------|----|----|----|--------|\n");

printf("|%-10s|%-15s|%4.0f|%4.0f|%4.0f|%8.2f|\n", pmax->studdata.no, pmax->studdata.name,pmax->studdata.score[0],pmax->studdata.score[1],pmax->studdata.score[2],pmax->studdata.sum);

printf("********************************end***********************\n"); }

3. 参考代码如下:

/*用插入法按由大到小排序函数*/ STUDENT *sort(STUDENT *h) {

STUDENT *p,*q,*t,*h1;

/*定义临时指针*/

h1=h->next->next;

/*从原表的第二个学生结点开始处理*/

h->next->next=NULL;

/*将原表的第一个学生结点作为有序表的第一个结点*/

while(h1!=NULL)

/*当还有元素没有插入到有序表时,进行排序*/

{

t=h1;

/*取未排序的第一个结点*/

h1=h1->next;

/*h1指针后移*/

p=h->next;

/*设定移动指针p,从第一个结点开始*/

q=h->next;

/*设定移动指针q做为p的前驱,指向第一个结点*/

while(p!=NULL && t->studdata.sum < p->studdata.sum ) /*作总分比较*/

{

q=p;

/*待排序点值小,则有序表指针后移*/

p=p->next;

}

if(p==q)

/*p==q,说明待排序点值大,应排在首位*/

{

t->next=p;

/*待排序点的后继为p*/

h->next=t;

/*新头结点为待排序点*/

}

else

/*待排序点应插入在中间某个位置q和p之间,如p为空则是尾部*/

{

t->next=p;

/*t的后继是p*/

q->next=t;

/*q的后继是t*/

}

}

printf("sort sucess!!!\n");

return h;

}

/*排序成功*/ /*返回头指针*/

"The C Programming Language", 2nd edition,

Kernighan and Ritchie 《c程序设计语言》英文的配套答案,所列页码均为英文版的。 1.01 1.02 1.03 1.04 1.05 1.06 1.07 1.08 1.09 1.10 1.11 1.12 1.13 1.14 1.15 1.16 1.17 1.18 1.19 1.20 1.21 1.22 1.23 1.24 2.01 2.02 2.03 2.04 2.05 2.06 2.07 2.08 2.09 2.10 3.01 3.02 3.03 3.04 3.05 3.06 4.01 4.02 4.03 4.04 4.05 4.06 4.07 4.08 4.12 4.13 4.14 5.01 5.02 5.03 5.04 5.05 5.06 5.07 5.08 5.09 5.10 5.11 5.13 5.14 6.01 6.03 6.04 6.05 7.01 7.02 7.03 7.06 7.08 7.09 8.01 8.03 8.04 8.06

Answer to Exercise 1-1

Run the "hello, world" program on your system. Experiment with leaving out parts of the program, to see what error messages you get.

Murphy's Law dictates that there is no single correct answer to the very first exercise in the book. Oh well. Here's a "hello world" program:

#include

int main(void) {

printf("hello, world\n");

return 0; }

As you can see, I've added a return statement, because main always returns int, and it's good style to show this explicitly. Answer to Exercise 1-2

Experiment to find out what happens when printf 's argument string contains \c, where c is some character not listed above.

By 'above', the question is referring to: \n (newline) \t (tab) \b (backspace) " (double quote) \ (backslash) We have to tread carefully here, because using a non-specified escape sequence invokes undefined behaviour. The following program attempts to demonstrate all the legal escape sequences, not including the ones already shown (except \n , which I actually need in the program), and not including hexadecimal and octal escape sequences.

#include

int main(void) {

printf("Audible or visual alert. \a\n");

printf("Form feed. \f\n");

printf("This escape, \r, moves the active position to the initial position of the current line.\n");

printf("Vertical tab \v is tricky, as its behaviour is unspecified under certain conditions.\n");

return 0; }

Answer to Exercise 1-3

Modify the temperature conversion program to print a heading above the table.

#include

int main(void) {

float fahr, celsius; int lower, upper, step;

lower = 0;

upper = 300;

step = 20;

printf("F C\n\n");

fahr = lower;

while(fahr <= upper)

{

celsius = (5.0 / 9.0) * (fahrstep;

}

return 0; }

This version uses a for loop:

#include

int main(void) {

float fahr, celsius;

int lower, upper, step;

lower = 0;

upper = 300; step = 20;

printf("C F\n\n");

for(celsius = upper; celsius >= lower; celsius = celsius20)

printf("%3d %6.1f\n", fahr, (5.0/9.0)*(fahr-32));

return 0; } Answer to Exercise 1-6

Verify that the expression getchar() != EOF is 0 or 1.

/* This program prompts for input, and then captures a character * from the keyboard. If EOF is signalled (typically through a * control-D or control-Z character, though not necessarily), * the program prints 0. Otherwise, it prints 1. *

* If your input stream is buffered (and it probably is), then * you will need to press the ENTER key before the program will * respond. */

#include

int main(void) {

printf("Press a key. ENTER would be nice :-)\n\n");

printf("The expression getchar() != EOF evaluates to %d\n", getchar() != EOF);

return 0; }

Answer to Exercise 1-7

Write a program to print the value of EOF .

#include

int main(void) {

printf("The value of EOF is %d\n\n", EOF);

return 0; }

Exercise 1-8

Write a program to count blanks, tabs, and newlines.

#include int main(void) {

int blanks, tabs, newlines;

int c;

int done = 0;

int lastchar = 0;

blanks = 0;

tabs = 0;

newlines = 0;

while(done == 0)

{

c = getchar();

if(c == ' ')

++blanks;

if(c == '\t')

++tabs;

if(c == '\n')

++newlines;

if(c == EOF)

{

if(lastchar != '\n')

{

++newlines; /* this is a bit of a semantic stretch, but it copes * with implementations where a text file might not * end with a newline. Thanks to Jim Stad for pointing * this out. */

}

done = 1;

}

lastchar = c;

}

printf("Blanks: %d\nTabs: %d\nLines: %d\n", blanks, tabs, newlines);

return 0; }

Exercise 1-9 Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.

#include

int main(void) {

int c;

int inspace;

inspace = 0;

while((c = getchar()) != EOF)

{

if(c == ' ')

{

if(inspace == 0)

{

inspace = 1;

putchar(c);

}

}

/* We haven't met 'else' yet, so we have to be a little clumsy */

if(c != ' ')

{

inspace = 0;

putchar(c);

}

}

return 0; }

Chris Sidi writes: "instead of having an "inspace" boolean, you can keep track of the previous character and see if both the current character and previous character are spaces:"

#include

/* count lines in input */ int main() {

int c, pc; /* c = character, pc = previous character */

/* set pc to a value that wouldn't match any character, in case this program is ever modified to get rid of multiples of other characters */

pc = EOF;

while ((c = getchar()) != EOF) {

if (c == ' ')

if (pc != ' ') /* or if (pc != c) */

putchar(c);

/* We haven't met 'else' yet, so we have to be a little clumsy */

if (c != ' ')

putchar(c);

pc = c;

}

return 0; }

Stig writes: "I am hiding behind the fact that break is mentioned in the introduction"!

#include

int main(void) {

int c;

while ((c = getchar()) != EOF) {

if (c == ' ') {

putchar(c);

}

while((c = getchar()) == ' ' && c != EOF)

; }

if (c == EOF)

break; /* the break keyword is mentioned

* in the introduction...

* */

putchar(c);

}

return 0;

Exercise 1-10

Write a program to copy its input to its output, replacing each tab by \t , each backspace by \b , and each backslash by \ . This makes tabs and backspaces visible in an unambiguous way.

Category 0 Gregory Pietsch pointed out that my solution was actually Category 1. He was quite right. Better still, he was kind enough to submit a Category 0 solution himself. Here it is:

/* Gregory Pietsch */

/*

* Here's my attempt at a Category 0 version of 1-10. *

* Gregory Pietsch */

#include

int main() {

int c, d;

while ( (c=getchar()) != EOF) {

d = 0;

if (c == '\') {

putchar('\'); putchar('\');

d = 1;

}

if (c == '\t') {

putchar('\');

putchar('t');

d = 1;

}

if (c == '\b') {

putchar('\');

putchar('b');

d = 1;

}

if (d == 0)

putchar(c);

}

return 0; }

Category 1

This solution, which I wrote myself, is the sadly discredited Cat 0 answer which has found a new lease of life in Category 1.

#include

#define ESC_CHAR '\'

int main(void) {

int c;

while((c = getchar()) != EOF)

{

switch(c)

{ case '\b':

/* The OS on which I tested this (NT) intercepts \b characters. */

putchar(ESC_CHAR);

putchar('b');

break;

case '\t':

putchar(ESC_CHAR);

putchar('t');

break;

case ESC_CHAR:

putchar(ESC_CHAR);

putchar(ESC_CHAR);

break;

default:

putchar(c);

break;

}

}

return 0; }

Exercise 1-11

How would you test the word count program? What kinds of input are most likely to uncover bugs if there are any?

It sounds like they are really trying to get the programmers to learn how to do a unit test. I would submit the following:

0. input file contains zero words 1. input file contains 1 enormous word without any newlines 2. input file contains all white space without newlines 3. input file contains 66000 newlines 4. input file contains word/{huge sequence of whitespace of different kinds}/word 5. input file contains 66000 single letter words, 66 to the line 6. input file contains 66000 words without any newlines 7. input file is /usr/dict contents (or equivalent) 8. input file is full collection of moby words 9. input file is binary (e.g. its own executable) 10. input file is /dev/nul (or equivalent)

66000 is chosen to check for integral overflow on small integer machines.

Dann suggests a followup exercise 1-11a: write a program to generate inputs (0,1,2,3,4,5,6)

I guess it was inevitable that I'd receive a solution for this followup exercise! Here is Gregory Pietsch's program to generate Dann's suggested inputs:

#include #include

int main(void) {

FILE *f;

unsigned long i;

static char *ws = " \f\t\v";

static char *al = "abcdefghijklmnopqrstuvwxyz";

static char *i5 = "a b c d e f g h i j k l m " "n o p q r s t u v w x y z " "a b c d e f g h i j k l m " "n o p q r s t u v w x y z " "a b c d e f g h i j k l m " "n\n";

/* Generate the following: */

/* 0. input file contains zero words */

f = fopen("test0", "w");

assert(f != NULL);

fclose(f);

/* 1. input file contains 1 enormous word without any newlines */

f = fopen("test1", "w");

assert(f != NULL);

for (i = 0; i < ((66000ul / 26) + 1); i++)

fputs(al, f);

fclose(f);

/* 2. input file contains all white space without newlines */

f = fopen("test2", "w");

assert(f != NULL);

for (i = 0; i < ((66000ul / 4) + 1); i++)

fputs(ws, f);

fclose(f);

/* 3. input file contains 66000 newlines */

f = fopen("test3", "w");

assert(f != NULL);

for (i = 0; i < 66000; i++)

fputc('\n', f);

fclose(f);

/* 4. input file contains word/

* {huge sequence of whitespace of different kinds} * /word */

f = fopen("test4", "w");

assert(f != NULL);

fputs("word", f);

for (i = 0; i < ((66000ul / 26) + 1); i++)

fputs(ws, f);

fputs("word", f);

fclose(f);

/* 5. input file contains 66000 single letter words, * 66 to the line */

f = fopen("test5", "w");

assert(f != NULL);

for (i = 0; i < 1000; i++)

fputs(i5, f);

fclose(f);

/* 6. input file contains 66000 words without any newlines */

f = fopen("test6", "w");

assert(f != NULL);

for (i = 0; i < 66000; i++)

fputs("word ", f);

fclose(f);

return 0; }

Exercise 1-12

Write a program that prints its input one word per line. #include int main(void) {

int c;

int inspace;

inspace = 0;

while((c = getchar()) != EOF)

{

if(c == ' ' || c == '\t' || c == '\n')

{

if(inspace == 0)

{

inspace = 1;

putchar('\n');

}

/* else, don't print anything */

}

else

{

inspace = 0;

putchar(c);

}

}

return 0; }

Exercise 1-13

Write a program to print a histogram of the lengths of words in its input. It is easy to draw the histogram with the bars horizontal; a vertical orientation is more challenging.

/* This program was the subject of a thread in comp.lang.c, because of the way it handled EOF. * The complaint was that, in the event of a text file's last line not ending with a newline,

* this program would not count the last word. I objected somewhat to this complaint, on the

* grounds that "if it hasn't got a newline at the end of each line, it isn't a text file". *

* These grounds turned out to be incorrect. Whether such a file is a text file turns out to

* be implementation-defined. I'd had a go at checking my facts, and had

* checked the wrong facts! (sigh) *

* It cost me an extra variable. It turned out that the least disturbing way to modify the

* program (I always look for the least disturbing way) was to replace the traditional

* while((c = getchar()) != EOF) with an EOF test actually inside the loop body. This meant

* adding an extra variable, but is undoubtedly worth the cost, because it means the program

* can now handle other people's text files as well as my own. As Ben Pfaff said at the * time, "Be liberal in what you accept, strict in what you produce". Sound advice. *

* The new version has, of course, been tested, and does now accept text files not ending in * newlines. *

* I have, of course, regenerated the sample output from this program. Actually, there's no

* "of course" about it1];

if(thisval > maxval)

{

maxval = thisval;

}

}

}

else

{

thisval = ++lengtharr[MAXWORDLEN];

if(thisval > maxval)

{

maxval = thisval;

}

}

} if(c == EOF)

{

done = 1;

}

}

else

{

if(inspace == 1 || firstletter == 1)

{

wordlen = 0;

firstletter = 0;

inspace = 0;

}

++wordlen;

}

}

for(thisval = maxval; thisval > 0; thisval--)

{

printf("%4d | ", thisval);

for(thisidx = 0; thisidx <= MAXWORDLEN; thisidx++)

{

if(lengtharr[thisidx] >= thisval)

{

printf("* ");

}

else

{

printf(" ");

}

}

printf("\n");

}

printf(" +");

for(thisidx = 0; thisidx <= MAXWORDLEN; thisidx++)

{

printf("---");

}

printf("\n ");

for(thisidx = 0; thisidx < MAXWORDLEN; thisidx++)

{

printf("%2d ", thisidx + 1);

}

printf(">%d\n", MAXWORDLEN);

return 0; }

Here's the output of the program when given its own source as input:

113 | * 112 | * 111 | * 110 | * 109 | * 108 | * 107 | * 106 | * 105 | * 104 | * 103 | * 102 | * 101 | * 100 | * 99 | * 98 | * 97 | * 96 | * 95 | * 94 | * * 93 | * * 92 | * * 91 | * * 90 | * * 89 | * * 88 | * * 87 | * * 86 | * * 85 | * * 84 | * * 83 | * * 82 | * * 81 | * * 80 | * * 79 | * * 78 | * * 77 | * * 76 | * * 75 | * * 74 | * * 73 | * * 72 | * * 71 | * * 70 | * * 69 | * * 68 | * * 67 | * * 66 | * * 65 | * * 64 | * * 63 | * * * 62 | * * * 61 | * * * 60 | * * * 59 | * * * 58 | * * * 57 | * * * 56 | * * * 55 | * * * 54 | * * * 53 | * * * 52 | * * * * 51 | * * * * 50 | * * * * 49 | * * * * 48 | * * * * 47 | * * * * 46 | * * * * 45 | * * * * 44 | * * * * 43 | * * * * * 42 | * * * * * 41 | * * * * * 40 | * * * * * 39 | * * * * * 38 | * * * * * 37 | * * * * * 36 | * * * * * 35 | * * * * * 34 | * * * * * 33 | * * * * * 32 | * * * * * 31 | * * * * * 30 | * * * * * * 29 | * * * * * * 28 | * * * * * * * 27 | * * * * * * * 26 | * * * * * * * 25 | * * * * * * * * 24 | * * * * * * * * 23 | * * * * * * * * 22 | * * * * * * * * * 21 | * * * * * * * * * 20 | * * * * * * * * * 19 | * * * * * * * * * 18 | * * * * * * * * * 17 | * * * * * * * * * 16 | * * * * * * * * * 15 | * * * * * * * * * 14 | * * * * * * * * * * 13 | * * * * * * * * * * 12 | * * * * * * * * * * 11 | * * * * * * * * * * 10 | * * * * * * * * * * 9 | * * * * * * * * * * * 8 | * * * * * * * * * * * 7 | * * * * * * * * * * * 6 | * * * * * * * * * * * 5 | * * * * * * * * * * * 4 | * * * * * * * * * * * 3 | * * * * * * * * * * * 2 | * * * * * * * * * * * 1 | * * * * * * * * * * * +-- 1 2 3 4 5 6 7 8 9 10 >10

Exercise 1-14 Write a program to print a histogram of the frequencies of different characters in its input.

Naturally, I've gone for a vertical orientation to match exercise 13. I had some difficulty ensuring that the printing of the X-axis didn't involve cheating. I wanted to display each character if possible, but that would have meant using isprint(), which we haven't yet met. So I decided to display the value of the character instead. (The results below show the output on an ASCII system(100 * (thisidx / 100))) / 10 );

}

}

printf("\n ");

for(thisidx = 0; thisidx < NUM_CHARS; thisidx++)

{

if(freqarr[thisidx] > 0)

{

printf("%d", thisidx32.0); return c; }

int main(void) {

float fahr, celsius;

int lower, upper, step;

lower = 0;

upper = 300;

step = 20;

printf("F C\n\n");

fahr = lower;

while(fahr <= upper)

{

celsius = FtoC(fahr);

printf("%3.0f %6.1f\n", fahr, celsius);

fahr = fahr + step;

}

return 0; }

Answer to Exercise 1-16, page 30

Revise the main routine of the longest-line program so it will correctly print the length of arbitrarily long input lines, and as much as possible of the text.

/* This is the first program exercise where the spec isn't entirely * clear. The spec says, 'Revise the main routine', but the true * length of an input line can only be determined by modifying * getline. So that's what we'll do. getline will now return the * actual length of the line rather than the number of characters * read into the array passed to it. */

#include #define MAXLINE 1000 /* maximum input line size */

int getline(char line[], int maxline); void copy(char to[], char from[]);

/* print longest input line */ int main(void) {

int len; /* current line length */

int max; /* maximum length seen so far */

char line[MAXLINE]; /* current input line */

char longest[MAXLINE]; /* longest line saved here */

max = 0;

while((len = getline(line, MAXLINE)) > 0)

{

printf("%d: %s", len, line);

if(len > max)

{

max = len;

copy(longest, line);

}

}

if(max > 0)

{

printf("Longest is %d characters:\n%s", max, longest);

}

printf("\n");

return 0; }

/* getline: read a line into s, return length */ int getline(char s[], int lim) {

int c, i, j;

for(i = 0, j = 0; (c = getchar())!=EOF && c != '\n'; ++i)

{

if(i < lim1)

{

s[j++] = c;

}

++i;

}

s[j] = '\0';

return i; }

/* copy: copy 'from' into 'to'; assume 'to' is big enough */ void copy(char to[], char from[]) {

int i;

i = 0;

while((to[i] = from[i]) != '\0')

{

++i;

} }

Chris Sidi, however, was not convinced1] != '\n')

{

if(getmore == 0)

copy(temp, line);

prevmax += len;

if(max < prevmax)

max = prevmax;

getmore = 1;

}

else

{

if(getmore == 1)

{

if(max < prevmax + len)

{

max = prevmax + len;

copy(longest, temp);

longest[MAXLINE1 && ((c = getchar()) != EOF && c != '\n');

++i)

s[i] = c;

if(c == '\n')

{

s[i] = c;

++i;

}

else if(c == EOF && i > 0)

{

/* gotta do something about no newline preceding EOF */

s[i] = '\n';

++i;

}

s[i] = '\0';

return i; }

void copy(char to[], char from[]) {

int i;

i = 0;

while((to[i] = from[i]) != '\0')

++i; }

Answer to Exercise 1-17, page 31 Write a program to print all input lines that are longer than 80 characters.

#include

#define MINLENGTH 81

int readbuff(char *buffer) {

size_t i=0;

int c;

while (i < MINLENGTH) {

c = getchar();

if (c == EOF) return -1;

if (c == '\n') return 0;

buffer[i++] = c;

}

return 1; }

int copyline(char *buffer) {

size_t i;

int c;

int status = 1;

for(i=0; iputchar(buffer[i]);

while(status == 1) {

c = getchar();

if (c == EOF)

status = -1;

else if (c == '\n')

status = 0;

else

putchar(c);

}

putchar('\n');

return status; }

int main(void) {

char buffer[MINLENGTH];

int status = 0;

while (status != -1) {

status = readbuff(buffer); if (status == 1)

status = copyline(buffer);

}

return 0; }

Answer to Exercise 1-18, page 31

Write a program to remove all trailing blanks and tabs from each line of input, and to delete entirely blank lines.

/* K&R2 1-18 p31: Write a program to remove trailing blanks and tabs from each line of input, and to delete entirely blank lines.

The program specification is ambiguous: does "entirely blank lines" mean lines that contain no characters other than newline, or does it include lines composed of blanks and tabs followed by newline? The latter interpretation is taken here.

This implementation does not use any features not introduced in the first chapter of K&R2. As a result, it can't use pointers to

dynamically allocate a buffer to store blanks that it has seen, so it must limit the number of blanks that are allowed to occur consecutively. (This is the value of MAXQUEUE, minus one.)

It is intended that this implementation "degrades gracefully." Even though a particular input might have 1000 or more blanks or tabs in a row, causing a problem for a single pass, multiple passes through the file will correct the problem. The program signals the need for such an additional pass by returning a failure code to the operating system. (EXIT_FAILURE isn't mentioned in the first chapter of K&R, but I'm making an exception here.) */

#include #include

#define MAXQUEUE 1001

int advance(int pointer) {

if (pointer < MAXQUEUERJH.

/* K&R2 1-18 p31: Write a program to remove trailing blanks and tabs from each line of input, and to delete entirely blank lines.

The program specification is ambiguous: does "entirely blank lines" mean lines that contain no characters other than newline, or does it include lines composed of blanks and tabs followed by newline? The latter interpretation is taken here.

This implementation does not use any features not introduced in the first chapter of K&R2. As a result, it can't use pointers to

dynamically allocate a buffer to store blanks that it has seen, so it must limit the number of blanks that are allowed to occur consecutively. (This is the value of MAXQUEUE, minus one.)

It is intended that this implementation "degrades gracefully." Even though a particular input might have 1000 or more trailing blanks or tabs in a row, causing a problem for a single pass, multiple passes through the file will correct the problem. The program signals the need for such an additional pass by returning a failure code to the operating system. (EXIT_FAILURE isn't mentioned in the first chapter of K&R, but I'm making an exception here.) */

#include #include

#define MAXQUEUE 1001

int advance(int pointer) {

if (pointer < MAXQUEUE1 && (c = getchar()) != EOF && c != '\n'; ++i)

{

s[i] = c;

}

if(c == '\n')

{

s[i++] = c;

}

s[i] = '\0';

return i;

}

int main(void) {

char line[MAX_LINE];

while(getline(line, sizeof line) > 0)

{

discardnewline(line);

reverse(line);

printf("%s\n", line);

}

return 0; }

Answer to Exercise 1-20, page 34

Thanks to Rick Dearman for pointing out that my solution used fgets() which has not been introduced by page 34. I've fixed the solution to use K&R's getline() function instead. Further thanks to Roman Yablonovsky who, in Oct 2000, pointed out that the solution was buggy, and hinted at a fix. Basically, the problem he spotted was that my solution failed to keep track of the cumulative effect of multiple tabs in a single line. I've adopted his fix (which was in fact also slightly buggy, but I've fixed that too). Write a program detab that replaces tabs in the input with the proper number of blanks to space to the next tab stop. Assume a fixed set of tab stops, say every n columns. Should n be a variable or a symbolic parameter?

#include #include #include

#define MAX_BUFFER 1024 #define SPACE ' ' #define TAB '\t'

int CalculateNumberOfSpaces(int Offset, int TabSize) {

return TabSize1 && (c = getchar()) != EOF && c != '\n'; ++i)

s[i] = c;

if(c == '\n')

{

s[i] = c;

++i;

}

s[i] = '\0';

return i; }

int main(void) {

char Buffer[MAX_BUFFER];

int TabSize = 5; /* A good test value */

int i, j, k, l;

while(getline(Buffer, MAX_BUFFER) > 0)

{

六、编程题参考答案

1.编程,统计在所输入的50个实数中有多少个正数、多少个负数、多少个零。 #include "stdio.h" #define N 50 void main() { float x; unsigned int s1,s2,s3,i; s1=s2=s3=0; for(i=1;i<=N;i++) { scanf("%f",&x); if(x<0) s1++; else if(x==0) s2++; else s3++; } printf("负数%u个,零%u个,正数%u个\n",s1,s2,s3); }

2. 编程,计算并输出方程 X2+Y2=1989 的所有整数解。 #include "stdio.h" void main() { int x,y; for(x=-45;x<=45;x++) { y=-45; while(y<=45) { if(x*x+y*y==1989) printf("%d*%d+%d*%d=%d\n",x,x,y,y,1989); y++; } } }

3.编程,输入一个10进制正整数,然后输出它所对应的八进制、十六进制数。 #include "stdio.h" void main() { unsigned int x; printf("请输入一个十进制正整数:"); scanf("%u",&x); printf("%d=八进制数 %o=十六进制数%x\n",x,x,x); }

4.编程,找出1000以内的所有完数,并输出其因子。 #include "stdio.h" void main() { int i,j,s=1; for(i=1;i<=1000;i++,s=1) { for(j=2;j<=i/2;j++) if(i%j==0) s+=j; // 求 i的因子和

if(s==i) { printf("%d=1",i); // 如果i 是完数则输出其各因子

for(j=2;j<=i/2;j++) if(i%j==0) printf("+%d",j); printf("\n"); } } }

5. 输入一个正整数,输出它的所有质数因子。 #include "stdio.h" void main() { int m,i=2; printf("请输入一个整数:"); scanf("%d",&m); while(m!=1) if(m%i==0){ printf("%d ",i); m/=i; } else i++; printf("\n"); }

6. 输入20个整数,输出其中能被数组中其它元素整除的那些数组元素。 #include "stdio.h" #define N 20 void main() { int a[N],i,j; for(i=0;i7. 输入两个数组(数组元素个数自定),输出在两个数组中都出现的元素。 #include "stdio.h" #define NA 6 #define NB 8 void main() { float a[NA],b[NB]; int i,j; for(i=0;i8. 输入两个数组(数组元素个数自定),输出在两个数组中都不出现的元素。 #include "stdio.h" #define NA 6 #define NB 8 void main() { float a[NA],b[NB]; int i,j; for(i=0;i9.编程,将字符数组S2中的全部字符拷贝到字符数组S1中。 #include "stdio.h" void main() { char s1[20],s2[]="Good morning!"; int i=0; while((s1[i++]=s2[i])!='\0'); printf("%s\n",s1); }

10.给定年份year,判别该年份是否闰年(定义一个宏以判别该年份是否闰年)。 #include #define f(year) year%4==0&&year%100!=0||year%400==0 void main() { int y; printf("请输入年份:"); scanf("%d",&y); if(f(y)) printf("%d 年为闰年\n",y); else printf("%d 年不是闰年\n",y); }

11.输入一行小写字母后,或输出原文,或将字母变成其下一字母(a变成b、b变成c、„、x变成y、y变成z、z变成a)输出,用条件编译方法实现以上选择。 #include #define MAX 80 #define SWITCH 1 void main() { char str[MAX]; int i=0; printf("请输入文本行:\n"); scanf("%s",str); #if(SWITCH) while(str[i]!='\0') if(str[i]>='a'&&str[i]<='z') if(str[i]=='z')str[i]='a'; else str[i]++; i++; #endif printf("%s\n",str); }

12. 编写函数,处理n行n列维数组:将每一行的元素同除以该行上绝对值最大的元素。

#include "stdio.h" #include "math.h" void div(float** a,int n) { int i,j; float x; for(i=0;ifabs(x)) x=*(*(a+i)+j); for(j=0;j{ float b[3][3]={{1,2,3},{4,5,6},{7,8,9}}; int i,j; float* c[3]; for(i=0;i<3;i++) c[i]=b[i]; div(c,3); for(i=0;i<3;i++) { for(j=0;j<3;j++) printf("%f ",b[i][j]); printf("\n"); } }

13. 编写函数,求任意阶多项式 a0+a1X+a2X2+...+anXn 的值并返回多项式的值。 #include "stdio.h" float f1(float* a,float x,int n) { int i; float t=1,y=0; for(i=0;i14. 设计一个函数,使给出一个数的原码,能得到该数的补码。

#include // 假定sizeof(int)为2;

unsigned int getbit(unsigned int value) //第1位为0表示数的原码,

{ if(value>>15) return (value^0x7fff)+1; //其补码即其原码;若value else return value; //右移15位后为1,表示value是负数的原码,负数

} //的补码为原码按位取反(第1位不变)后加1。

void main() { unsigned int y=0x800c,k; k=getbit(y); printf("%x\n",k); }

15. 编写函数,求m行、n列的二维数组全体元素中负数的个数。 #include int sum(float **a,int m,int n) { int i,j; int y=0; for(i=0;i{ float b[2][3]={{-1,2,-3},{4,-5,-6}}; int i; float* c[2]; for(i=0;i<2;i++) c[i]=b[i]; printf("%d\n",sum(c,2,3)); } 16. 编写函数,返回在一个整数组中出现次数最多的数及其出现次数。 #include void fun(float *a,int n,int *k,float *x) { int i,j,y; *k=0; for(i=0;i*k) { *k=y; *x=*(a+i); } } return; } void main() // 函数引用示例

{ float c[10]={0,4,2,4,3,2,4,-3,1.5,7.6},t; int m; fun(c,10,&m,&t); // 若说明float *t; int *m; printf("元素%f出现次数为%d\n",t,m); // 引用为 fun(c,10,m,t) 将

} // 产生悬挂指针的错误,即t、m不只指向确定的存储单元。

17.编一个程序,打入月份号,输出该月的英文月名,要求用指针数组处理。 #include void main() { char *month_name[12]={"January","February","March","April", "May", "June","July","August","September","October", "Novenber","December"}; int n; printf("请输入月份号:"); scanf("%d",&n); if(n<1||n>12) printf("月份号输入错误!\n"); else printf("%d月的英文表示是%s\n",n,month_name[n-1]); }

18.编写递归函数,将输入的以“?”结束的字符串按与输入相反的顺序输出。 #include void pline() { char ch; if((ch=getchar())!='?') { pline(); putchar(ch); } return; } void main() // 函数引用示例 { pline(); printf("\n"); }

19. 编写函数,在n个元素的一维数组中,统计比相邻元素大的数组元素个数并将统计数返回(不考虑a[0]和a[n-1]),要求以指针变量而不是数组名作参数。 #include int num(float *x,int n) { int i,k=0; for(i=1;i*(x+i-1)&&*(x+i)>*(x+i+1)) k++; return k; } void main() // 函数引用示例

{ float a[10]={1,3,4,2,6,7,12,5,9,8}; printf("%d\n",num(a,10)); }

20. 编写函数,在n个元素的一维数组中,找出最大值、最小值并传送到调用函数。

#include void num(float *b,int n,float *max,float *min) { *max=*b; *min=*b; for(int i=1;i*max) *max=*(b+i); if(*(b+i)

{ float a[10]={1,3,4,2,6,7,12,5,9,8},x,y; num(a,10,&x,&y); printf("最大值为%f,最小值为%f。\n",x,y); }

21. 编写一个函数,统计m行n列二维数组中有多少个正数、多少个负数,多少个零,并

返回统计结果。

#include void sub(float** a,int m,int n,int *fs,int *lin,int *zs) { int i,j; *fs=*lin=*zs=0; for(i=0;i{ float b[5][3]={{-1,5,2},{3,0,-2},{0,-3,5}, {4,7,-8},{3,4,5}},*c[5]; int i,k1,k2,k3; for(i=0;i<5;i++) c[i]=b[i]; sub(c,5,3,&k1,&k2,&k3); printf("负数%d个,零%d个,正数%d个。\n",k1,k2,k3); }

22. 编写函数,在给定的一行以'.'结束的字符中,找出最长的单词并输出。 #include void find(char *str) { char *p1,*p2,*p3; int k1=0,k2=0; // k1为最长串的长度,初值为0。

p1=p2=p3=str; // p3指向最长串首字符,p1指向当前处理串首字符,

while(*p2!='.') // p2为移动指针,*p2为空格表示查找到单词尾部。

if(*p2!=' ') { k2++; p2++; } else if(k2>k1) { p3=p1; p1=++p2; k1=k2; k2=0; } else { k2=0; p1=++p2; } for(k2=0;k2<=k1;k2++) printf("%c",*(p3+k2)); printf("\n"); return; } void main() // 函数引用示例 { char a[40]; int i=0; while((a[i++]=getchar())!='.'); find(a); }

23. 编写函数print,打印一个学生的成绩数组,该数组中有若干个学生的数据记录,每个记录包括num,name,score[3]。 #include struct student { char num[7],name[9];int score[3]; }; // 尾部分号不得遗漏

void print(struct student* s,int n) { int i; // 运算符'*'、'&'的优先级均低于运算符'.' for(i=0;iprintf("%s %s %4d%4d%4d\n",(*(s+i)).num,(*(s+i)).name,

(*(s+i)).score[0],(*(s+i)).score[1],(*(s+i)).score[2]); return; } void main() { struct student t[4]; int i; for(i=0;i<4;i++)

scanf("%s%s%d%d%d",&t[i].num,&t[i].name,&t[i].score[0], &t[i].score[1],&t[i].score[2]); print(t,4); } 24. 把文本文件d1.dat复制到文本文件d2.dat中,要求仅复制d1.dat中的英文字符。

#include void main() { FILE *fpd1,*fpd2; char ch; fpd1=fopen("d1.dat","r"); fpd2=fopen("d2.dat","w"); while(fscanf(fpd1,"%c",&ch)!=EOF) if(ch>='A'&&ch<='Z'||ch>='a'&&ch<='z') fprintf(fpd2,"%c",ch); fclose(fpd1); fclose(fpd2); }

25. 编程,把文本文件d1.dat复制到d2.dat(其中空格字符不复制)。 #include void main() { FILE *fpd1,*fpd2; char ch; fpd1=fopen("d1.dat","r"); fpd2=fopen("d2.dat","w"); while(fscanf(fpd1,"%c",&ch)!=EOF) if(ch!=' ') fprintf(fpd2,"%c",ch); fclose(fpd1); fclose(fpd2); }

26. 编程,把文本文件d1.dat复制到d2.dat(其中大写英文字母要转换为小写字母)。

#include void main() { FILE *fpd1,*fpd2; char ch; fpd1=fopen("d1.dat","r"); fpd2=fopen("d2.dat","w"); while(fscanf(fpd1,"%c",&ch)!=EOF) { if(ch>='A'&&ch<='Z') ch=ch+32; fprintf(fpd2,"%c",ch); } fclose(fpd1); fclose(fpd2); }

27. 把文本文件d1.dat复制到文本文件d2.dat中,要求仅复制d1.dat中除英文字符和数字以外的其它内容。 #include void main() { FILE *fpd1,*fpd2; char ch; fpd1=fopen("d1.dat","r"); fpd2=fopen("d2.dat","w"); while(fscanf(fpd1,"%c",&ch)!=EOF)

if(!(ch>='A'&&ch<='Z'||ch>='a'&&ch<='z'||ch>='0'&&ch<='9')) fprintf(fpd2,"%c",ch); fclose(fpd1); fclose(fpd2); }

28. 求出1至100之间的素数(只能被1和自身整除的数)并顺序写入文件su.dat。

#include #include void main() { FILE *fp; int i,j,k=2; fp=fopen("su.dat","w"); fprintf(fp,"%4d%4d",2,3); for(i=5;i<100;i=i+2) { for(j=3;j<=sqrt(i);j=j+2) if(i%j==0) break; if(j>sqrt(i)) { fprintf(fp,"%4d",i); k++; if(k%10==0) fprintf(fp,"\n"); } } fclose(fp); }

29.磁盘文件a1和a2,各自存放一个已按字母顺序排好的字符串,编程合并二个文件到a3 文件中,合并后仍保持字母顺序。 #include #include void main() { FILE *fp1,*fp2,*fp3; int i,j,k; char c1,c2; fp1=fopen("a1","r"); fp2=fopen("a2","r"); // 首先从文件a

1、a2中各读入一个字符分别送入变量c

1、c2,下面将作

// 循环比较,直到读到文件尾标志为止。

fp3=fopen("a3","w"); c1=fgetc(fp1); c2=fgetc(fp2); do { if(c130.顺序文件C.DAT每个记录包含学号(8位字符)和成绩(三位整数)两个数据项。从文件读入学生成绩,将大于或等于60分的学生成绩再形成一个新的文件SCORE60.DAT保存在A盘上,并显示出学生总人数、平均成绩和及格人数。 #include #include void main() { FILE *fp1,*fp2; char s[9]; int x,zrs=0,pjcj=0,jgrs=0; fp1=fopen("c.dat","r"); fp2=fopen("a:score60.dat","w"); fscanf(fp1,"%s%d",s,&x); do { zrs++; pjcj+=x; if(x>=60) { jgrs++; fprintf(fp2,"%s %d\n",s,x); } fscanf(fp1,"%s%d",s,&x); } while(!feof(fp1)); printf("总人数:%d 平均成绩:%d 及格人数:%d\n",zrs,pjcj/zrs,jgrs); fclose(fp1); fclose(fp2); } 31.程序清单:

typedef int datatype; typedef struct node {datatype data; struct node *next; }linklist; „„

INVERT(linklist *head) {linklisk *p,*q; p=head->next; if(p!=NULL) {head->next=NULL; do {q=p->next; p->next=head->next; head->next=p; p=q; } while(p!=NULL); } } 32.程序清单:

PURGE(linklist *head) {linklist *p,*q; q=head->next; if(q==NULL)return; p=q->next; while(p!=NULL) if(p->data==q->data) {q=p->next; free(p); p=q->next; } else {q=p; p=p->next; } }

33、程序清单: #include main() {static char x[]=”computer”; char *p; for(p=x;p34、#include #include main() {int m; char str[80],str2[80]; printf(“input a string:\n”); gets(str2); printf(“intput m:\n); scanf(“%d”,&m); if(strlen(str2)35、程序清单:

float search(float (pointer)[4],int n) {float *pt; pt=*(pointer+n); return(pt); }

36、Main() {int score[][4]={{60,76,80,90},{45,86,57,90},{58,95,80,71},{78,50,60,85}}; int (*p)[4],j,k,flag; p=score; for(j=0,j<4;j++) if(*(*(p+j)+k)<60)flag=1; if(flag==1) {printf(“NO.%dis fail,svoreare:\n”,j); for(k=0,;k<4;k++) printf(“%5d”, *(*(p+j)+k);

printf(“\n”); } }

37、程序清单: main() {int b[16],x,k,r,I; printf(“enter a integer :\n”): scanf(“%d”,&x);

printf(%6d’s binary number is:\n”,x); k=-1; do {r=x%2; k++; *(b+k; x/=2; }while(x!=0 for(I=k;I>=0;I--) printf(“%d”,*(b+i) printf(“\n”); } 38、float p(int n,int x) {flaot t,t1,t2; if(n==0)return(1); else if(n==1) return(x); else {t1=(2*n-1)*x*(p((n-1),x)); t2=(n-1)*p((n-2),x); t=(t1-t2)/n); return(t); }}

39、main() {int a[5][5],I,j,k=0,m,n; m=n/2+1; for(I=0,I=I;j--) {k++;a[n-I-1][j]=k;} for(j=n-2-I;j>=I+1;j--) {k++;a[I][j];}} for(I=0;Imain() {int m[16],n,I,t,count=0; long a,k; printf(“result is:\n”); for(n=10;n<200;n++) {k=0; t=1; a=n*n; for(I=1;a!=0;I++) {m[I]=a%10; a/=10; } for(;I>1;I--) {k+=m[I-1]*t; t=t*10; } if(k==n*n) printf(“%2d:%10d%10d\n”,++count,n,N*n); }}

41、

void convert(char *a,int n) {int I; if((I=n/10)!=0) convert(a+1,i); *a=n%10+’0’; }

42、#include main() {FILE *fp; char str[100],fikename[10]; int I=0; if((fp=fopen(“upper.txt”,”w”))==NULL) {printf(“can not open file\n”); exit(0); } printf(“enter a string:\n”); gets(str); while(str[I]!=’!’)

{if(str[I]>=’a’&&str[I]<=’z’) str[I]=str[I]-32; fputc(str[I],fp); I++; } fclose(fp); }

43、#include “stdio.h” FILE *fp; main() {int p=0,n=0,z=0,temp; fp=fopen(“number.dat”,”r”); if(fp==NULL) printf(“file not found\n”); else {while(!feof(fp)) {fscanf(fp,”%d”,&temp); if(temp>0) p++; else if(temp<0) n++; else z++; } fclose(fp); printf(“posive:%3d,negtive:%3d,zero:%3d\n:,p,n,z); } }

44、main() {unsigned rightrot(unsigned a,int n)

unsigned int m,b;

int n;

printf(“enter mand n:”);

scanf(%x,%d”,&m,&n);

printf(“m=%x,n=%d\n”,m,n);

b=rightrot(m,n);

printf(“b=%x\n”,b); } unsigned rightrot(unsigned a,int n) {int rb; while(n0) {rb=(a&1)<>1; a=a|rb; } return a; }

45、解:PX(X,N)=X-X2+X3-X4+„„+(-1)N-1XN =X*(1- X-X2+X3-X4+„„+(-1)N-1XN-1 =X*(1-PX(X,N-1) 程序清单:

double px(double x,int n) {if(n==1) return x; else return(x*(1-px(x,n-1)); }

46、程序清单:

double opwer1(double x,int n) {if(n==0) return 1; else return(x*power1(x,n-1); }

47、Printfn(int n) {if(n=0&&n<=9) printf(“%d”,n); else {printf(“%d”,x%10); printn(x/10); } }

48、程序清单: t(int n) {int m; printf(“%d”,x%10); m=x/10; if(m>0) r(m); }

49、程序清单:

int ack(int m,int n) {if(m==0) return (n+1); else if(n==0) return(ack(m-1,1); else return(ack(m-1,ack(m,n-1))); } 50、Void intobin(int x) {if(x/2>0) intobin(x/2); printf(“%d”,x%2); }

51、Void intobin(int x) {if(x/8>0) intobin(x/8); printf(“%d”,x%8); }

52、Void intobin(int x) { if(x/16>0) intobin(x/16); printf(“%c”,(x%16>=9)?x%16+55:x%16+48); }

53、Main() {int x; printf(“enter a number:\n”);

scanf(“%d”,&x); if(x!=0) {if(x>0) { x=x%2; if(x) printf(“this number is a plus odd number\n”); else printf(“this number is a plus even number\n”); } else { x=x%2; if(x) printf(“this number is a plus odd number\n”); else printf(“this number is a plus even number\n”); } else printf(“this number is zero\n”); }

54、Main() {int x,y,max; printf(“please input two number:\n”);

scanf(“%d,%d”,&x,&y); if(a>b) max=a; else max=b; printf(“max=%d”,max); }

55、Main() {int j; for(j=999;j>=100;j--) if(555555%j==0) break; printf(“%d”,j); }

56、Main() {int I,count,j,sum; sum=count=0; for(I=0;I<10;I++) {printf(“input ingter:\n); scanf(“%d”,&j); if(j<0) continue; count++; sum=sum+j; } if(count) printf(“plus number:%d,average value :%.2f”,count,1.0*sum/count); else printf(“plus number:0,average value :0”); }

57、Main() {int year; printf(“%d”,&year); if(year<0) printf(“year is not a yaer\n”): else if((year%4==0&&year%100!=0)||year%400==0) printf(“year is leap year!\n”); else printf(“year is not leap year!\n”); }

58、main() {int n,j,k; printf(“input n:\n”);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值