本文提供經典教材《C與指標》第四章部分習題的參考代碼,涵蓋數值計算、數論、條件判斷、字符串處理等核心考點。
#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;
}
#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;
}
#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;
}
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';
}
substrvoid 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';
}
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';
}
assert或單元測試驗證邊界情況。