循环内打印变量出现无限输出及数字转英文单词代码求助
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

