4.1正数的n的平方根可以通过:
ai+1= (ai + n / ai ) / 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;
}
4.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;
}
4.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;
}