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

循环内打印变量出现无限输出及数字转英文单词代码求助

Troubleshooting Infinite Loop in Number-to-Words Conversion Code

Hey there! As a fellow coding beginner, I totally get how frustrating infinite loops can be—let's break down what's going on here and fix that first, then we can tackle the rest of your number-to-words logic if you need extra help.

The Root Cause of Your Infinite Loop

Looking at your loop to calculate the maximum magnitude of the input number:

while ((number / pow(10, i)) >= 1) {
    i++;
}

The problem lies with using pow(), which returns a floating-point double value. Floating-point operations often have tiny precision errors—for example, pow(10, 3) might actually evaluate to something like 999.9999999999999 instead of exactly 1000. When you divide your integer number by this imprecise value, the result could be slightly greater than 1 even when it should logically be exactly 1, causing the loop condition to stay true forever.

A Simple Fix for the Loop

Replace the floating-point pow() with integer arithmetic—this eliminates precision issues entirely. Here's how to rewrite that loop:

int magnitude = 1;
while (number / magnitude >= 10) {
    magnitude *= 10;
    i++;
}

By using only integers, there's no ambiguity about whether the division result meets the condition. The magnitude variable will correctly track the highest power of 10 that fits into your input number, and the loop will exit as expected.

Quick Tips for Your Number-to-Words Logic

Since you mentioned your code feels a bit tedious, here are two small tips to simplify it later:

  • Create helper functions for small number ranges (like 1-19, 20-90) to avoid repeating the same string assignments over and over.
  • Break the input number into chunks (hundreds, thousands, millions, etc.)—English number words follow a consistent pattern for these groups, which will make your code easier to organize.

内容的提问来源于stack exchange,提问作者Jithakrishna Prakash

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:14:06