gpt4 book ai didi

C. 我的数字以相反的顺序打印(英文)?我怎样才能解决这个问题?

转载 作者:太空宇宙 更新时间:2023-11-04 05:51:59 30 4
gpt4 key购买 nike

请多多指教!我正在完成“C 语言编程”一书中的练习。

我必须编写一个程序,它接受一个整数,然后提取并用英语显示整数的每一位。

因此,如果我输入 1234,它应该打印回“一二三四”。

由于这个练习接近本书的开头,它还没有教授数组、函数、指针或字符串。我认为这意味着我不允许使用它们中的任何一个。所以我必须用非常有限的选项以某种方式解决它。

我写的内容或多或少有效,但数字以相反的顺序打印回来。我真的很难找到一个替代方案,并且一直在研究过去几个人的代码。

我意识到几年前发布了另一个非常相似的问题,但我在这个问题上能做的更有限,更不用说,他/她的问题要复杂得多。

如果您能看一看并提供一些建议,我将不胜感激。

#include <cs50.h>
#include <stdio.h>

int main (void)
{
int digit;

//Accept integer
printf("Choose a number.\n");

int num = GetInt();

// adding minus to the beginning if int is negative
if (num < 0)
{
num = -num;
printf("minus ");
}

// isolate each digit from integer and then print in english

do
{
digit = num % 10;

switch(digit)
{
case 0:
printf("Zero ");
break;
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 10:
printf("Ten ");
break;
default:
break;
}

num /= 10;

} while(num != 0);

printf("\n");
}

最佳答案

假设你不能使用递归,因为你不能定义你自己的函数,你需要一个初始循环来找到最左边的数字位置。

以下代码使用 place 变量将 10 提高到“位数减 1”,将零视为单个数字。主循环将(剩余部分)数字除以 place,打印出该数字,然后减少数字模 place 并除以 place下一次迭代增加 10,直到打印完所有数字(当 place 为零时)。

#include <cs50.h>
#include <stdio.h>

int main (void)
{
int digit;

//Accept integer
printf("Choose a number.\n");

int num = GetInt();

// adding minus to the beginning if int is negative
if (num < 0)
{
num = -num;
printf("minus ");
}

// get 10 to the power of 'number of digits minus 1'
int place;

for (place = 1; place <= num / 10; place *= 10)
;

// isolate each digit from integer and then print in english

do
{
digit = num / place;

switch(digit)
{
case 0:
printf("Zero ");
break;
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;
default:
break;
}

num %= place;
place /= 10;

} while (place != 0);

printf("\n");
}

关于C. 我的数字以相反的顺序打印(英文)?我怎样才能解决这个问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38378946/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com