首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

《C與指標》第四章語句習題精選解答:平方根、質數、三角形、字符串操作

     編輯:關於C語言

《C與指標》第四章習題解答精選 (VS2012驗證)

本文提供經典教材《C與指標》第四章部分習題的參考代碼,涵蓋數值計算、數論、條件判斷、字符串處理等核心考點。

1. 牛頓迭代法求平方根

#include <stdio.h>
double sqrt_newton(double n) {
    if (n < 0) return -1;
    double x = 1.0, prev;
    do {
        prev = x;
        x = (prev + n / prev) / 2;
    } while (x != prev); // 浮點數直接比較相等在收斂時通常安全
    return x;
}
int main() {
    double n; printf("Input N: "); scanf("%lf", &n);
    printf("sqrt(%.2f) = %.6f\n", n, sqrt_newton(n));
    return 0;
}

2. 1~100質數篩選 (試除法)

#include <stdio.h>
#include <math.h>
bool is_prime(int n) {
    if (n < 2) return false;
    for (int i = 2; i * i <= n; ++i)
        if (n % i == 0) return false;
    return true;
}
int main() {
    printf("Primes 1-100: ");
    for (int i = 1; i <= 100; ++i)
        if (is_prime(i)) printf("%d ", i);
    return 0;
}

3. 三角形分類判斷

#include <stdio.h>
int main() {
    int a, b, c;
    printf("Input a,b,c: ");
    do { scanf("%d%d%d", &a, &b, &c); }
    while (a+b<=c || a+c<=b || b+c<=a); // 確保能構成三角形
    if (a==b && b==c) puts("Equilateral");
    else if (a==b || b==c || c==a) puts("Isosceles");
    else puts("Scalene");
    return 0;
}

4. 字符串複製 copy_n (指定長度,不足補\0)

正確實現:

void copy_n(char dst[], const char src[], int n) {
    int i = 0;
    for (; i < n && src[i]; ++i) dst[i] = src[i];
    for (; i < n; ++i) dst[i] = '\0';
}

5. 子串提取 substr

void substr(char dst[], const char src[], int start, int len) {
    int src_len = 0; while (src[src_len]) src_len++;
    if (start < 0 || len < 0 || start >= src_len) { dst[0] = '\0'; return; }
    int i = 0;
    for (; i < len && src[start+i]; ++i) dst[i] = src[start+i];
    dst[i] = '\0';
}

6. 刪除多餘空格 deblank (只保留單個空格)

void deblank(char str[]) {
    int i = 0, j = 0;
    bool space_pending = false;
    while (str[i]) {
        if (str[i] == ' ') {
            if (!space_pending) { str[j++] = ' '; space_pending = true; }
        } else {
            str[j++] = str[i]; space_pending = false;
        }
        ++i;
    }
    str[j] = '\0';
}

💡 學習建議

  • 字符串操作題核心在於邊界條件(空串、長度不足、\0處理)。
  • 優先寫出清晰正確的版本,再考慮優化。
  • 善用assert或單元測試驗證邊界情況。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved