使用 do-while 迴圈實作牛頓迭代法,直到前後兩次估值相等。
#include <stdio.h>
double sqrt_newton(double temp) {
double before = 1.0, after = 1.0;
do {
before = after;
after = (before + temp / before) / 2;
} while (before != after);
return after;
}
int main() {
double temp, result;
puts("input N:");
scanf("%lf", &temp);
result = sqrt_newton(temp);
printf("sqrt N = %lf\n", result);
return 0;
}
雙重迴圈試除法,計算因數個數,若恰為 2 則為質數。
#include <stdio.h>
int main() {
int length = 100;
puts("Prime(1~100):");
for (int i = 1; i <= length; i++) {
int divisors = 0;
for (int j = 1; j <= i; j++) {
if (i % j == 0) divisors++;
}
if (divisors == 2) printf("%d ", i);
}
return 0;
}
輸入三邊長,先驗證能否構成三角形(任意兩邊之和大於第三邊),再判斷等邊、等腰或不等邊。
#include <stdio.h>
int main() {
int a, b, c;
puts("輸入三邊長度(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("等邊!");
else if (a==b || b==c || c==a) puts("等腰!");
else puts("不等邊!");
return 0;
}
copy_n 實作錯誤嘗試:先算來源長度再複製,邏輯繁瑣且易錯。
正確做法:單一迴圈,複製時同步檢查來源是否結尾,結尾後補 \0 至 n 個字元。
void copy_n(char dst[], char src[], int n) {
int dst_index, src_index = 0;
for (dst_index = 0; dst_index < n; dst_index++) {
dst[dst_index] = src[src_index];
if (src[src_index] != '\0') src_index++;
}
}
substr參數:目標陣列、來源陣列、起始位置、長度。需處理越界情況(起始或長度為負、起始超過來源長度),回傳空字串。
void substr(char dst[], char src[], int start, int len) {
int src_len = 0;
while (src[src_len] != '\0') src_len++;
if (start < 0 || len < 0 || start >= src_len) {
dst[0] = '\0';
return;
}
for (int i = 0; i < len; i++) {
dst[i] = src[start + i];
if (dst[i] == '\0') break; // 來源提前結尾
}
dst[len] = '\0'; // 確保結尾
}
deblank將連續空白壓縮為單一空白,使用暫存陣列複製法。
void deblank(char string[]) {
char copy[1000]; // 假設足夠大
int i = 0, j = 0, space_flag = 0;
for (i = 0; string[i] != '\0'; i++) {
if (string[i] == ' ') {
if (space_flag) continue; // 跳過連續空白
space_flag = 1;
} else {
space_flag = 0;
}
copy[j++] = string[i];
}
copy[j] = '\0';
// 複製回原陣列
for (i = 0; copy[i] != '\0'; i++) string[i] = copy[i];
string[i] = '\0';
}
\0 結尾判斷與指標/索引操作。const 修飾輸入參數,讓編譯器協助防禦誤寫。