返回首页 C++ 模板

while循环模板

未知循环次数时使用:条件驱动型循环

while循环 条件循环 GESP1
#include <bits/stdc++.h>
using namespace std;

int main() {
    // 求位数
    int n = 12345, temp = n, digits = 0;
    while (temp > 0) { digits++; temp /= 10; }
    cout << digits << endl;  // 5

    // 读入直到条件满足
    int x, sum = 0;
    while (cin >> x && x != 0) sum += x;

    // while(true) + break
    int target = 42, guess;
    while (true) {
        cin >> guess;
        if (guess == target) break;
    }

    // 牛顿迭代法求 √2
    double a = 2.0, x0 = 1.0;
    while (fabs(x0 * x0 - a) > 1e-9)
        x0 = (x0 + a / x0) / 2.0;

    return 0;
}

📖 要点说明

⚠️ 常见错误