如何修复将用户输入数字转为单词输出时多打印零的问题?
Let's break down what's going wrong and how to fix it step by step, like a fellow developer troubleshooting with you.
First: Why That Extra Zero Shows Up
Looking at your code, here's the exact root cause:
- Your first loop counts the number of digits in the input. For example, entering
123makes this loop run 3 times, soibecomes 3. - Your second loop uses the condition
o <= i. Sinceostarts at 0, this means the loop runs 4 times (o=0,1,2,3) instead of the 3 times you need. - On the 4th iteration,
chas already been divided by 10 three times (so it's 0), sop = c%10gives 0—hence the random extra "zero" in your output.
Quick Fix for the Extra Zero
Just tweak the second loop's condition from:
while(o<=i) {
to:
while(o < i) {
Bonus: Fix the Reverse Order Problem
Wait, you might have missed another issue too—right now entering 123 outputs three two one (after fixing the zero), but your goal is one-two-three. That's because you're pulling digits from the right to left (using %10 grabs the last digit first). To fix this, we can store digits in an array first, then print them left to right.
Here's the revised full code that fixes both issues and matches your desired output format:
#include<stdio.h> int main() { int i=0, a, c, o=0, p; int digits[10]; // Array to store digits (works for numbers up to 10 digits) printf("Enter the number you want: "); scanf("%d", &a); c = a; // Count digits and store each one in the array while(c != 0) { digits[i] = c % 10; c = c / 10; i++; } // Print digits in the original number's order while(o < i) { p = digits[i - 1 - o]; // Grab digits from last stored to first switch(p) { case 1: printf("one"); break; case 2: printf("two"); break; case 3: printf("three"); break; case 4: printf("four"); break; case 5: printf("five"); break; case 6: printf("six"); break; case 7: printf("seven"); break; case 8: printf("eight"); break; case 9: printf("nine"); break; case 0: printf("zero"); break; } // Add hyphen only between words, not at the end if(o != i-1) { printf("-"); } o++; } printf("\n"); return 0; }
Key Improvements in the Revised Code:
- Added an array to store digits as we extract them, so we can reverse the order later
- Used a
switchstatement for cleaner digit-to-word mapping (optional, but makes the code neater) - Added logic to print hyphens only between words, matching your example format
- Fixed the loop condition to eliminate the extra zero
Now if you enter 123, you'll get the exact output you want: one-two-three.
内容的提问来源于stack exchange,提问作者user9256954

