码迷,mamicode.com
首页 > 其他好文 > 详细

第三章 习题

时间:2016-08-14 07:14:14      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

 3.1正数的n的平方根可以通过:

ai+1= (a+ n / a) / 2

  得到,第一个a1是1,结果会越来越精确。

#include <stdio.h>

int main() 
{
	double input;
	double exp;
	scanf_s("%lf", &input);

	double aBefore = 1;
	double aNow = (aBefore + input / aBefore) / 2;

	exp = aBefore - aNow;
	exp = exp < 0 ? -exp : exp;
	printf("aBefore: %lf, aNow: %lf, exp: %f\n\n", aBefore, aNow, exp);
	while (exp > 0.000001) {
		aBefore = aNow;
		aNow = (aBefore + input / aBefore) / 2;
		exp = aBefore - aNow;
		exp = exp < 0 ? -exp : exp;
		printf("aBefore: %lf, aNow: %lf, exp: %lf\n", aBefore, aNow, exp);
	}

	return 0;
}

  技术分享

 3.2 打印100以内的质数

  因为2* 50 和 50 *2一样,如果按照1 2 3 4 一直遍历到目标的数其实有很多重复,事实上只需要计算到这个数的平方根即可停止。

  

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

#define TRUE 1
#define FALSE 0

int isPrimer(int num)
{
	int idx;
	int end = floor(sqrt(num)) + 1;
	for (idx = 2; idx <= end ; idx++)
	{
		if (num % idx == 0) {
			return FALSE;
		}
	}
	return TRUE;
}
int main() 
{
	int num;
	for (num = 1; num <= 100; num++)
	{
		if (isPrimer(num)) {
			printf("%d ", num);
		}
	}

	return 0;
}

  技术分享

3.7去除字符串中多余的空格

#include <stdio.h>

void trim(char str[])
{
	//判断之前是否在空格中
	int inEmpty = 0;
	//字符串下标
	int idx = 0;

	//循环字符串
	while (str[idx] != ‘\0‘) {
		//遇到空格
		if (str[idx] == ‘ ‘ || str[idx] == ‘\t‘ || str[idx] == ‘\n‘) {
			//如果之前不是空格,设置空格状态为1
			if (!inEmpty) {
				inEmpty = 1;
				idx++;
			}else{
				//如果之前是空格将之后的字符全部前移一位
				int len = strlen(str);
				for (int movStart = idx; movStart <= len; movStart++) {
					str[movStart] = str[movStart + 1];
				}
			}
		}else {
			//没遇到空格需要恢复非空格状态
			inEmpty = 0;
			idx++;
		}
	}
}

int main()
{
	char name[] = "  this is my           name";
	printf("%s\n", name);
	trim(name);
	printf("%s\n", name);

	return 0;
}

  技术分享

 

第三章 习题

标签:

原文地址:http://www.cnblogs.com/yangxunwu1992/p/5769164.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!