谭浩强C程序设计第四版答案

只给出一些需要编程的答案,用的是谭浩强老师的书:

本文持续更新中…

C程序设计课本中的一些笔记见:C程序设计笔记

我的目录

第一单元

6,编写一个c程序,输入a,b,c三个值,输出其中最大者
#include<stdio.h>
int main()
{
	int a, b, c,d;
	int max(int x, int y, int z);
	printf("enter three number:");
	scanf_s("%d,%d,%d", &a, &b, &c);
	d = max(a, b, c);
	printf("max=%d\n", d);
	return 0;

}
int max(int x, int y, int z)
{
	int max;
	max = x;
	if (max < y)
		max = y;
	if(max<z) 
		max = z;
	return max;

}

使用c++库函数只能比较两个数max(),min()里面只能放两个数。因此可以使用max(max(a,b),c)的方法比较三个数
https://wenku.baidu.com/view/f34993086137ee06eef91811.html?rec_flag=default&sxts=1543935291260

#include<stdio.h>   //预处理
#include<algorithm>  
using namespace std;    //使用命名空间std
int main()    //主函数首部
{         //函数体开始
	int x, y, z, max_num;     //定义变量
	printf("Enter three numbers:");
	scanf_s("%d,%d,%d", &x, &y, &z);
	max_num = max(x, y);
	printf("最大值是:%d\n", max_num);
	return 0;
}    //函数结束

第二单元

2.1 什么是算法,试从日常生活中找出2个例子,描述它们的算法

书中给出:
程 序 = 算 法 + 数 据 结 构 程序=算法+数据结构 =+
算法是对操作的描述,即要求计算机进行操作的步骤,广义而言:为解决一个问题而采取的方法和步骤就是“算法”。更具体而言:数据结构是加工/操作对象,语言是工具,算法则是灵魂。
举例1:过年买火车票回家,回家需要先收拾行李,去车站,订票,付款,拿票,上车,此处还有很多过程,比如转车等等,到家。而算法就是这一系列的步骤,算法的优化就是针对某一方向,比如要最快最经济的到家,采取一些手段使得达到这个目的。
举例2:烹饪;需要先买菜,洗菜,切菜,烹饪一大堆的过程,最后放调味品。
所以从上面看到,实际上过程就是算法,所以是
在这里插入图片描述
图片来源:Ribbon什么是算法
博主写得很详细,建议去看看

2.2 什么是结构化的算法,为什么要提倡结构化的算法

由基本结构所构成的算法叫做“结构化”的算法,其中基本结构即三个基本结构:顺序结构,选择结构和循环结构。
结构化算法通过基本结构可以使得一个复杂的问题更加简化易读,同时也易修改,将复杂问题简单化,让编程更容易,提高代码维护和可读性(后一句来自百度百科)

2.6 用伪代码表示第4题中各题的算法

这里我就不写伪代码了,直接上代码
(1)

第三单元

3.1 假如我国国民生产总值的年增长率为9%,计算10年后我国国民生产总值与现在相比增长多少百分比。计算公式为:

p = ( 1 + r ) n p=(1+r)^n p=(1+r)n

#include <stdio.h>
#include <math.h>

int main()
{
   /* 计算增长百分比 */
   float r=0.09,p;
   int n=10;
   p=pow(1+r,n);
	printf("%.3f",p);

   return 0;
}
3.2 存款利息的计算。现有1000元,想存5年,有五种办法。
每种办法得到的结果分别为:
#include <stdio.h>
#include <math.h>

int main()
{
   /* 本息和 */
   float p0,p1,p2,p3,p4,r0=0.0072,r1=0.0414,r2=0.0468,r3=0.0540,r4=0.0585;
   int p=1000;
	
	p0=p*(1+5*r4);    //一次存五年
	p1=p*(1+2*r2)*(1+3*r3);  //先存2年再存3年
	p2=p*(1+3*r3)*(1+2*r2);   //先存两年后存3年
	p3=p*pow(1+r1,5);   //连续存5年,一次一年
	p4=p*pow(1+r0/4.0,4*5);
   printf("p0=%f\n,p1=%f\n,p2=%f\n,p3=%f\n,p4=%f",p0,p1,p2,p3,p4);

   return 0;
}

p0=1292.500000
,p1=1270.763062
,p2=1270.763184
,p3=1224.863770
,p4=1036.622314
可以看到存5年定期会更有收益

补充:
  • 上面的输出结果前有一个逗号,是因为printf()里面两个变量之间我都写了一个逗号(沿用python),所以如果要没有逗号,对于C语言而言,两个参数之间不需要任何符号(也不要空格,否则也会直接输出空格,C是按照从输出的左开始,当遇到格式声明符号%时开始替换,然后又继续一一输出,直到下一个%)。
  • 将上面的存款改为1万或者十万,依然是存5年定期最多,活期最小(因为银行是鼓励存定期的)
3.3 多少个月还完贷款。
#include <stdio.h>
#include <math.h>

int main()
{
   int d=300000,p=6000;
	float r=0.01,m,n,l;
	
	m=log10(p/(p-d*r))/log10(1+r);
	printf("一共需要%.1f还清",m);

   return 0;
}

一共需要69.7还清

补充:

69.7*6000=418200接近42万,贷了30万要还六年共42万,吃人的银行。。。。

3.4 分析下面的程序
#include <stdio.h>
#include <math.h>

int main()
{ char c1,c2;
 c1=97;
 c2=98;
 printf("c1=%c,c2=%c\n",c1,c2);
 printf("c1=%d,c2=%d\n",c1,c2);
   
 return 0;
}

(1)运行时的结果
c1=a,c2=b
c1=97,c2=98

分析:

这是赋值or输出过程中的类型转换问题。首先定义/声明c1,c2是字符型,内存只分配一个字节。97,98的ASCII码(P337)对应的字符为a,b。所以第一个输出是以字符输出(P97页输出方式),为a,b。第二个输出是以整数输出,为97,98.

(2)
好不容易写了很多之后,莫名其妙没有自动保存,浪费的几个小时真是绝望。。。。。。。吐槽CSDN!(毕竟有贴了图片,然后把原图删了,我到哪里找原图?!)
算了,再写一遍。不全写了。
在这里插入图片描述

3.5用下面的scanf函数输入数据,。。。。。

解答:这个题中scanf或者scanf_s的一些坑见:https://blog.csdn.net/Mr_Cat123/article/details/88563165

源码为:
在这里插入图片描述

#include<stdio.h>

int main()
{
	int a, b;
	float x,y;
	char c1, c2;
	scanf_s("a=%db=%d", &a, &b);
	scanf_s("%f%f", &x, &y);
	scanf_s("%c%c", &c1,sizeof(c1), &c2,sizeof(c2));
	printf("a=%d,b=%d\n",a, b);
	printf("x=%f,y=%f\n", x, y);
	printf("c1=%c,c2=%c", c1, c2);
	return 0;
}

当输入时在a=3 b=7两者间空一格则会出问题,这是因为输入要求是整型,当遇到空格(字符)就会停止输入。因此记住:scanf_s写入一定要跟里面的内容一致。如果没有空格就不要写空格(如果没有a=%db=%d,而是直接%d%d则可以空一格,如输入x,y就需要这样)
正确答案如下:
在这里插入图片描述
记住:如果是整型或者浮点型,如果没有像(a=%db=%d)而是直接(%d%d)则中间需要空一格。上面源码的第8行到第9行是从整型到浮点型,因此输完b=7之后按回车,因为a,b都是整型,当遇到字符立马就结束,而紧接着的x是浮点型。当输完y之后一定不能回车,因为紧接着是字符型,一旦输入回车,将会把回车作为第一个输入,即c1.

3.6 请编程序将。。。
#include<stdio.h>

int main()
{
	char c1='C', c2='h', c3='i', c4='n', c5='a';
	c1 = c1 + 4;
	c2 = c2 + 4;
	c3 = c3 + 4;
	c4 = c4 + 4;
	c5 = c5 + 4;
	printf("password is %c%c%c%c%c\n", c1,c2,c3,c4,c5);
	return 0;
}

在这里插入图片描述

3.7 设圆半径r=1.5.。。。。
#include<stdio.h>
#include<math.h>

int main()
{
	float r = 1.5, h = 3, l, s, sq, vq, vz;
	float pi = 3.14159265;
	printf("Please enter radius and height:r=  h=  (Separate the two parameters with Spaces)");
	scanf_s("%f %f", &r, &h);
	l = 2 * pi*r;
	s = pi*pow(r, 2);
	sq = 4 * pi*pow(r, 2);
	vq = 3.0 / 4.0 * pi*pow(r, 3);
	vz = pi*pow(r, 2)*h;
	printf("圆周长为:       l=%6.2f\n", l);
	printf("圆面积为:       s=%6.2f\n", s);
	printf("圆球表面积为:   sq=%6.2f\n", sq);
	printf("圆球体积为:     vq=%6.2f\n", vq);
	printf("圆柱体积为:     vz=%6.2f\n", vz);
		
	return 0;
}

在这里插入图片描述

注意:上面代码是3.0/4.0不是3/4,后者是0

第四单元

4.1 什么是算术运算?什么是关系运算?什么是逻辑运算?

算术运算:利用算术运算符进行加减乘除等的数学运算。
关系运行:关系运算即比较运算,利用关系运算符(<,<=,>,>=,==,!=)对两个数值进行比较的运算过程。
逻辑运算:利用逻辑运算符(&&,||,!)进行的运算。

4.3 写出下面各逻辑表达式的值。设a=3,b=4,c=5.

(1) a+b>c&&b==c
结果为0. 因为a+b=7>c=5,所以&&左边是真,用1表示。右边b==c用0表示。所以1&&0结果为0
(2)a||b+c&&b-c
结果为1。第93页的优先级别,算术运算符高于关系运算符,所以上面左边变成3||9为真,用1表示。右边为-1,故为1&&-1,都不是0,故为真,用1表示。
剩下几个一样的逻辑,自己分析。

4.4 3个整数,键盘输入,求最大值

此处采用两个方法,
1调用函数,
调用的是<windows.h>中的max函数,如果不写using namespace std则每个max都要改为std::max

#include<stdio.h>
#include<math.h>
#include<windows.h>
using namespace std;

int main()
{
	int a, b, c,max_value;
	scanf_s("%d%d%d", &a, &b, &c);
	max_value = max(max(a, b), c);
	printf("%d", max_value);

	return 0;
}

2 用条件表达式

#include<stdio.h>
#include<math.h>
#include<windows.h>
using namespace std;

int main()
{
	int a, b, c,function(int,int,int);
	scanf_s("%d%d%d", &a, &b, &c);
	printf("%d", function(a,b,c));

	return 0;
}
int function(int x, int y, int z)
{
	int max_value = (x > y) ? x : y;
	return (max_value > z) ? max_value : z;

}
4.5 从键盘输入一个小于1000的正数,要求输出它的平方根。。。。
#include<stdio.h>
#include<math.h>
#include<windows.h>
using namespace std;

int main()
{
	int num, num1;
	printf("Please enter a positive number which is less than 1000: ");
	scanf_s("%d", &num);
	if (num >= 1000 || num <= 0)
	{
		printf("Warning, please check whether the number is positive and less than 1000\nEnter again: ");
		scanf_s("%d", &num);
	}
	num = sqrt(num);
	printf("%d", num);

	return 0;
}

4.7 有一函数:。。。

结论:两个程序都不能实现,记住:else是跟最近的if搭配(P100上面第一行),如果else和if的数量不一样,则要用花括号。正确如下:

#include<stdio.h>
#include<math.h>
#include<windows.h>
using namespace std;

int main()
{
	float x;
	int y;
	scanf_s("%f", &x);
	if (x > 0)
		y = 1;
	else
		if (x == 0) y = 0;
		else y = -1;
		printf("%d", y);
	return 0;
}

4.8 给出一百分制成绩,要求输出成绩等级。。。。

这里我使用了while,使得可以结束完一次之后进入下一次循环

#include<stdio.h>
#include<math.h>
#include<windows.h>
using namespace std;

int main()
{
	float score;
	char grade;
	while (TRUE)
	{
		printf("Please enter your score: ");
		scanf_s("%f", &score);
		if (score > 100 || score < 0)
		{
			printf("Please check your input score,enter again: ");
			scanf_s("%f", &score);
	     }
		switch (int (score/10))
		{
		case 10:
		case 9:grade = 'A'; break;
		case 8:grade = 'B'; break;
		case 7:grade = 'C'; break;
		case 6:grade = 'D'; break;
		case 5:
		case 4:
		case 3:
		case 2:
		case 1:
		case 0:grade = 'E'; break;

		}
		printf("Your grade is %c\n", grade);
	}
	return 0;
}

4.9 给一个不多于5位的正整数,要求:…
#include<stdio.h>
#include<math.h>
#include<windows.h>
using namespace std;

int main()
{
	int num,place,ten_thousand,thousand,hundred,ten,individual;
	printf("Please enter a positive number (0-99999):");
	scanf_s("%d", &num);
	if (num > 9999)
		place = 5;
	else if (num > 999)
		place = 4;
	else if (num > 99)
		place = 3;
	else if (num > 9)
		place = 2;
	else place = 1;
	printf("Digit:%d", place);
	printf("Each number is: ");
	ten_thousand = num / 10000;
	thousand = (num - ten_thousand * 10000) / 1000;
	hundred = (num - ten_thousand * 10000 - thousand * 1000) / 100;
	ten = (num - ten_thousand * 10000 - thousand * 1000 - hundred * 100) / 10;
	individual = (num - ten_thousand * 10000 - thousand * 1000 - hundred * 100-ten*10);
	switch (place)
	{
	case 5:printf("%d,%d,%d,%d,%d\n", ten_thousand, thousand,hundred,ten,individual);
		printf("Inverse number:");
		printf("%d,%d,%d,%d,%d\n", individual,ten,hundred,thousand,ten_thousand);
	}

	return 0;
}

上面只给了五位数的例子,如10483,如果要加4,3,2,1位数,在switch下加case 4,case 3,即可。

4.10 企业发放的奖金。。。

这里我使用if编写,switch就不写了,比较简单。

#include<stdio.h>
#include<algorithm>
#include<functional>
using namespace std;

int main()
{
	float profit,bonus;
	printf("Please input profit:");
	scanf_s("%f", &profit);
	if (profit < 100000)
		bonus = profit*0.1;
	else if (profit < 200000)
		bonus = 100000 * 0.1 + (profit - 100000)*0.075;
	else if (profit < 400000)
		bonus = 100000 * 0.1 + 100000 * 0.075 + (profit - 200000)*0.05;
	else if (profit<600000)
		bonus= 100000 * 0.1 + 100000 * 0.075 + 200000*0.05+(profit - 400000)*0.03;
	else if (profit<1000000)
		bonus = 100000 * 0.1 + 100000 * 0.075 + 200000 * 0.05 + 200000*0.03+(profit - 600000)*0.015;
	else bonus = profit*0.01;
	printf("Your bonus is %.2f", bonus);

	return 0;
}

在这里插入图片描述

4.11 输入4个。。。

这个可以使用sort函数实现,见 https://blog.csdn.net/Mr_Cat123/article/details/88714096 第一个函数

4.12 有4个圆塔。。。

这个题乍一看有点棘手,实际上有了思路很简单。
重点是判断点是否在圆塔内,在则塔高10米,不在则为0. 而判断是否在塔内,只需要计算点p(x,y)到各个塔的中心点是否<=1即可,小于则在塔内,否则在塔外。

#include<stdio.h>
#include<algorithm>
#include<functional>
using namespace std;

int main()
{
	float x1 = 2, y1 = 2, x2 = -2, y2 = 2, x3 = -2, y3 = -2, x4 = 2, y4 = -2,d1, d2, d3, d4,height,x,y;
	printf("Please input the coordinate of the point p(x,y):");
	scanf_s("%f%f", &x, &y);
	d1 = pow((x - x1), 2) + pow((y1 - y), 2);
	d2 = pow((x2 - x), 2) + pow((y - y2), 2);
	d3 = pow((x3 - x), 2) + pow((y - y3), 2);
	d4 = pow((x4 - x), 2) + pow((y - y4), 2);
	if (d1 <= 1 || d2 <= 1 || d3 <= 1 || d4 <= 1)
		height = 10;
	else height = 0;
	printf("The height of the point:%.2f", height);

	return 0;
}

第五单元

5.2 请补充5.7程序…
#include<stdio.h>
#include<algorithm>
#include<time.h>
#define SUM 10000
using namespace std;

int main()
{
	clock_t timeStart, timeEnd;
	timeStart = clock();
	int i = 0, sign = 1;
	double n = 1.0, pi = 0.0;
	for (; fabs(1.0 / n) >= 1e-6; i++)
	{
		pi = pi + sign / n;
		sign = -sign;
		n = n + 2;
	}
	timeEnd = clock();
	printf("%f\n%d\n", 4 * pi, i);
	printf("time interval=%.4f\n", (float)(timeEnd - timeStart) / CLOCKS_PER_SEC);

	return 0;
}

在这里插入图片描述
上面的时间单位是秒,即0.01秒

5.4 请输入一行字符,分别统计其中英文字母,空格,数字和其他字符的个数。

这个题比较有意思,比上面一些题都好玩。首先,这个题在NLP(自然语言处理)中有一定的用处,比较实用。
大家想到输入一行字符,肯定会想到用scanf_s(%s)来输入,很遗憾,scanf_s遇到空格就退出了,如下所示
在这里插入图片描述
所以需要用gets()来输入,如:

#include<stdio.h>

using namespace std;

int main()
{
	char str[10];
	printf("Please enter a line of character:");
	gets_s(str);
	printf("%s\n", str);

	return 0;
}

在这里插入图片描述
方法1,实用gets()

#include<stdio.h>
#include<string.h>
using namespace std;

int main()
{
	char str[50];
	int letters = 0, space = 0, digit = 0, other = 0;
	unsigned i;
	printf("Please enter a line of character:");
	gets_s(str);
	printf("%s\n", str);
	for (i = 0; i <= strlen(str); i++)
	{
		if (str[i] >= 'a'&&str[i]<='z' ||str[i] >= 'A'&&str[i]<='Z') letters++;
		else if (str[i] == ' ') space++;
		else if (str[i] >= '0'&&str[i]<='9') digit++;
		else other++;
	}
	printf("The length of string is %d\nletters=%d\nspace=%d\ndigit=%d\nother=%d\n",strlen(str), letters, space, digit, other-1);

	return 0;
}

注意上面我最后输出的时候将other-1,这是因为在输入完成时候按回车即\n结束,而这个键被记录进去了,所以减1.同时,我将i定义为unsigned是因为strlen(str)用于计算长度时是正数,不会出现负数,所以不需要用有符号的整数,另外也防止报错:<=有符号/无符号不匹配
在这里插入图片描述
方法2,提供思路如下:使用getchar(),每次输入一个字符,当getchar()!=\n就while一直循环。

5.5 求 S n = a + a a + a a a + a a a a + a a a a a . . . S_n=a+aa+aaa+aaaa+aaaaa... Sn=a+aa+aaa+aaaa+aaaaa...,其中…

提示:比如输入a=2,n=5.
则第一个数是a,第二数是 a × 10 + a a\times10+a a×10+a,第三个数是 ( a × 10 + a ) × 10 + a (a\times10+a)\times10+a (a×10+a)×10+a,第四个数是 ( ( a × 10 + a ) × 10 + a ) × 10 + a ((a\times10+a)\times10+a)\times10+a ((a×10+a)×10+a)×10+a,可以看到这些数是相关联的

#include<stdio.h>
#include<string.h>
using namespace std;

int main()
{
	int a, n,i=1,sum,f;
	printf("Please enter a and n:");
	scanf_s("%d%d", &a, &n);
	sum = f = a;
	while (i < n)
	{
		f = f*10 + a;
		sum = sum + f;
		i++;
	}
	printf("%d\n", sum);
	return 0;
}
5.6 求 Σ 1 20 n ! = ( 1 ! + 2 ! + 3 ! + 4 ! + . . . ) \Sigma_{1}^{20}n!=(1!+2!+3!+4!+...) Σ120n!=(1!+2!+3!+4!+...)

方法1

提示:这道题可以先定义一个函数factorial()用于求乘积,如4!=4*3*2*1.再通过循环求和。如下

#include<stdio.h>
#include<string.h>
using namespace std;

int main()
{
	int j,n=20;
	long long factor,sum=0, factorial(int);
	//printf("%lld\n", ans);
	for (j = 1; j <= n; j++)
	{
		factor = factorial(j);
		sum = sum + factor;
	}
	printf("%lld\n", sum);

	return 0;
}
long long factorial(int n)
{
	int i;
	long long fact = 1;
	for (i = 1; i <= n; i++)
		fact = fact*i;
	return fact;
}

注意,由于要计算量很大,因为20!很大,所以采用了long long类型,否则会出现溢出得负数等问题。
在这里插入图片描述
另外,(长)整型是不能指数输出的,即不能(%e),而且,从课本可以看到,double类型比long long int可以储存更多,因此建议用double类型,即代码如下:

#include<stdio.h>
#include<string.h>
using namespace std;

int main()
{
	int j,n=20;
	double factor,sum=0, factorial(int);
	//printf("%lld\n", ans);
	for (j = 1; j <= n; j++)
	{
		factor = factorial(j);
		sum = sum + factor;
	}
	printf("%e\n", sum);


	return 0;
}
double factorial(int n)
{
	int i;
	double fact = 1;
	for (i = 1; i <= n; i++)
		fact = fact*i;
	return fact;
}

在这里插入图片描述
方法2

方法1使用了构建函数的方法,比较直观,而且在其他地方使用时还可以调用函数,是比较好用的。但就这个题本身,不需要调用这么多的函数,观察这个题的结构,跟上面一题很像。这个题的结构是,先连乘再求和。连乘和求和都可以使用替换的方法,即在循环体中,t=t*n和s=s+n这样的形式。

#include<stdio.h>
#include<string.h>
using namespace std;

int main()
{
	int n = 20, i=1;
	double t = 1, s = 0;
	while (i <= n)
	{
		t = t*i;
		s = s + t;
		i++;
	}
	printf("%e\n", s);

	return 0;
}

得到一样的结果
在这里插入图片描述

5.7 求 Σ k = 1 100 k + . . . \Sigma_{k=1}^{100}k+... Σk=1100k+...

C/C++语言

#include<stdio.h>
#include<string.h>
#include<math.h>
using namespace std;

int main()
{
	double sum1=0,sum2=0,sum3=0;
	int k;
	for (k = 1; k <= 100; k++)
	{
		sum1 = sum1 + k;
	}
	for (k = 1; k <= 50; k++)
	{
		sum2 = sum2 + pow(k, 2);
	}
	for (k = 1; k <= 10; k++)
	{
		sum3 = sum3 + 1.0 / k;
	}
	printf("%.3lf", sum1 + sum2 + sum3);

	return 0;
}

在这里插入图片描述
像这种连乘连加的问题,python的确写起来简单很多,以下用python写的代码:

import numpy as np

ans = np.sum([k for k in range(1,101)])+np.sum([k**2 for k in range(1,51)])+np.sum([1/k for k in range(1,11)])
print(ans)

在这里插入图片描述
一般而言,大家都说python比较慢,因此我计算以下两者花的时间。
因为计算实在太快了,所以我在k^2那一项加了五个0,C代码如下

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<time.h>

using namespace std;

int main()
{
	clock_t timestart, timeend;
	timestart = clock();
	double sum1=0,sum2=0,sum3=0;
	int k;
	for (k = 1; k <= 100; k++)
	{
		sum1 = sum1 + k;
	}
	for (k = 1; k <= 5000000; k++)
	{
		sum2 = sum2 + pow(k, 2);
	}
	for (k = 1; k <= 10; k++)
	{
		sum3 = sum3 + 1.0 / k;
	}
	timeend = clock();
	printf("%.3lf\n", sum1 + sum2 + sum3);
	printf("It took me %.8lf seconds\n", ((float)(timeend - timestart)) / CLOCKS_PER_SEC);

	return 0
}

在这里插入图片描述

import numpy as np
import time

start = time.time()
ans = np.sum([k for k in range(1,101)])+np.sum([k**2 for k in range(1,500001)])+np.sum([1/k for k in range(1,11)])
print(ans)
end = time.time()
print("Running time is:",end-start)

在这里插入图片描述
显然python比C慢10倍以上。

以下只做13题,剩下的有时间再写

5.13 用迭代法求 x = ( a ) x=\sqrt(a) x=( a)
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<time.h>

using namespace std;

int main()
{
	float a,x0,x1;
	printf("Please enter a positive number:");
	scanf_s("%f", &a);
	x0 = a/2;
	do
	{
		x1 = (x0 + a / x0) / 2.0;
	} while (fabs(x0 - x1) > 1e-5);
	printf("The sqrt of %.2f is %.2f\n", a, x1);

	return 0;
}

第六单元

6.1 用筛选法求100之内的素数
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<time.h>
#include<cstring>

using namespace std;

int main()
{
	int j,i,a[101],n;
	for (i = 0; i <= 100; i++)
		a[i] = i;
	for(i=2;i<sqrt(100);i++)
		for (j = i + 1; j <= 100; j++)
		{
			if (a[i] != 0 && a[j] != 0)
			{
				if (a[j] % a[i] == 0) a[j] = 0;
			}
		
		}
	for (i = 2,n=0; i <= 100; i++)
	{
		if (a[i] != 0)
		{
			printf("%5d", a[i]);
			n++;
		}
		if(n%10==0)
		{
			printf("\n");
		}
	}
	printf("\n");
	return 0;
}

在这里插入图片描述

6.2用选择法对10个整数排序

这里输入10个数太麻烦,我只输入5个

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<time.h>
#include<cstring>

using namespace std;

int main()
{
	int j,i,a[10],t;
	printf("Please input 10 integer number:\n");
	for (i = 0; i < 5; i++)
		scanf_s("%d", &a[i]);
	for(i=0;i<10;i++)
		for (j = i + 1; j < 5; j++)
		{
			if (a[j] < a[i])
			{
				t = a[j]; a[j] = a[i]; a[i] = t;
			}
			
		}
	for (i = 0; i < 5; i++)
		printf("%5d", a[i]);
	printf("\n");
	return 0;
}

在这里插入图片描述

6.3求一个3*3的整数矩阵对角线之和
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<time.h>
#include<cstring>

using namespace std;

int main()
{
	int a[3][3];
	int i, j,sum=0;
	printf("Enter data:\n");
	for (i = 0; i < 3; i++)
		for (j = 0; j < 3; j++)
			scanf_s("%d", &a[i][j]);
	for (i = 0; i < 3; i++)
	{
		sum = sum + a[i][i];
	}
	printf("%d", sum);
	printf("\n");
	return 0;
}

在这里插入图片描述

6.4 有一个已排好序的数组,要求输入一个数后,按原来排序规律插入数组中。

思路:(假如输入的都是整数,排序也是整数,并假设排好的数组是a[11],即一共有10个数,从a[0]~a[9],a[10]是用来放即将进来的数。注意没有a[11])
1, 先将输入的数nu与排序中的数a[9]对比,因为a[9]最大,假如a[9]<nu,则将nu赋给a[10]
2, 假如a[9]>nu,则开始遍历数组,找到a[i]>nu, 则将a[i]临时赋给变量temp,并将nu赋给a[i];
3, 将大于i的数都往后移动一位(这个用for循环就可以,我们先从最后一个移动,用j–)
代码如下:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<time.h>
#include<cstring>

using namespace std;

int main()
{
	//int a[11] = { 1,2,3,4,5,6,7,8,9,10 };
	int a[11] = { 2,4,8,10,32, 45,60,71,74,80 };
	int i, j,temp,nu;
	printf("Enter a number:\n");
	scanf_s("%d", &nu);
	for(i=0;i<10;i++)
		if (a[i] > nu)
		{
			temp = a[i];
			a[i] = nu;

			for (j = 9; j > i; j--)
			{
				a[j + 1] = a[j];
			}
			a[i + 1] = temp;
			break;
		}
		else a[10] = nu;
	for (i = 0; i < 11; i++)
		printf("%6d", a[i]);
	printf("\n");
	return 0;
}

在这里插入图片描述

6.5 将一个数组的值按逆时针排序…

1,调用sort函数:见https://blog.csdn.net/Mr_Cat123/article/details/88714096 第一个函数

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<functional>

using namespace std;

int main()
{
	int a[] = {8,6,5,4,1};
	int i;
	sort(a, a + 5, less<int>());
	for (i = 0; i < 5; i++)
		printf("%5d", a[i]);
	printf("\n");
	return 0;
}

2 自己动手写

#define _crt_secure_no_warnings
#include<stdio.h>
#include<math.h>

using namespace std;

int main()
{
	int a[] = {8,6,5,4,1};
	int i,temp;
	int len = sizeof(a) / sizeof(a[0]); //get the length of a
	//printf("The length of array a is %d\n", len);
	for (i = 0; i < len/ 2;i++)
	{
		temp = a[i];
		a[i] = a[len-1 - i];
		a[len-1 - i] = temp;
	}
	for (i = 0; i < 5; i++)
		printf("%5d", a[i]);
	printf("\n");
	return 0;
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Mr_Cat123/article/details/84800905
今日推荐