You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C语言编写for循环输出2的前30次幂?

Hey there! Let's figure out how to print the first 30 powers of 2 smoothly. I’ll walk through common pitfalls and share working code examples for popular languages, plus tips to debug whatever might be going wrong with your current code.

Common Issues to Check First

Before diving into code, let’s cover the most frequent mistakes that trip people up:

  • Off-by-one errors: If your loop stops too early or starts at the wrong exponent, you’ll end up with fewer (or extra) values. For the first 30 powers, we want 2^1 up to 2^30—so make sure your loop runs 30 times, covering exponents 1 through 30.
  • Integer overflow: In statically typed languages like Java or C++, using a 32-bit int for 2^30 is okay (since 2^30 = 1073741824, which is under the max int value of 2147483647), but going beyond that will cause overflow. Stick to long or unsigned types if you ever need to compute higher powers.
  • Incorrect initialization: If you’re multiplying by 2 iteratively, start with result = 2 (for 2^1) and multiply by 2 each loop, or start with 1 and shift/multiply to get 2^0 first—just be consistent with your exponent counting.

Working Code Examples

Python

Python handles big integers natively, so overflow isn’t a worry here. This script will print each power clearly:

# Print 2^1 through 2^30 (30 total powers)
for exponent in range(1, 31):
    power = 2 ** exponent
    print(f"2^{exponent} = {power}")

Java

For Java, use long to avoid any overflow risks (even though 2^30 fits in an int, using long keeps it safe for future adjustments):

public class PowerOfTwoPrinter {
    public static void main(String[] args) {
        // Loop from 1 to 30 to get the first 30 powers
        for (int exp = 1; exp <= 30; exp++) {
            // Bit shifting is more efficient than Math.pow() for integer powers of 2
            long result = 1L << exp;
            System.out.printf("2^%d = %d%n", exp, result);
        }
    }
}

C++

If you’re using C++, use unsigned long long to handle large values without overflow:

#include <iostream>
#include <iomanip>

int main() {
    for (int exp = 1; exp <= 30; ++exp) {
        unsigned long long result = 1ULL << exp;
        std::cout << "2^" << exp << " = " << result << std::endl;
    }
    return 0;
}

If you can share your existing code, I can help pinpoint exactly what’s going wrong with it!

内容的提问来源于stack exchange,提问作者Shahriar Kabir Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:48:21