C和指针 第四章 习题
生活随笔
收集整理的這篇文章主要介紹了
C和指针 第四章 习题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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 0int 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') {//如果之前不是空格,設置空格狀態為1if (!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; }
?
轉載于:https://www.cnblogs.com/yangxunwu1992/p/5769164.html
總結
以上是生活随笔為你收集整理的C和指针 第四章 习题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Struts2小结
- 下一篇: K-Means ++ 算法