gpt4 book ai didi

c - 练习 5.6 Kochan 的 C 语言编程

转载 作者:行者123 更新时间:2023-11-30 17:22:23 24 4
gpt4 key购买 nike

我无法获得解决此问题的功能程序(Kochan 的“C 语言编程”中的练习 5.6。目标是让程序接受输入数字,例如 123,并输出“一二三”。

现在,我有两个循环,结果是我想要输出的数字(2345 中的等式)2 将是所需的输出。我还希望跟踪多个并从初始表达式中减去。所以 2345 将输出 2,然后循环,并从 2345 中减去 2000。该程序应该计算 345,输出 3,并减去 300 等。然后我会担心将其转换为单词。

经过几个小时的工作后,我想知道是否存在我遗漏的根本缺陷。

作为引用,下一章是数组。这本书涵盖了循环(for、while、判断、if、else、switch)

到目前为止我得到的代码如下。我正在努力让它循环,并且已经为此奋斗了好几天。我所要展示的只是下面的代码,无可否认,它比我开始时要干净得多。下面显示的部分有效,但是当我尝试循环它时它失败了。到了这个地步,我只是尝试一切,但无济于事。再次,我希望下面的内容能够循环。

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
int number, counter, output;

printf ("Please input your number\n");
scanf (" %i", &number);

for (counter = 0; number > 9; counter = counter +1){
number = number /10;
output = number;
}

while (counter != 0){
number = number * 10;
counter = counter - 1;
}

printf ("%i %i\n", number, output);

return 0;
}

最佳答案

我尝试实现您在问题中陈述的概念,这是您的代码,并进行了一些更改以使其正常工作!希望它有帮助!!

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
int number, counter, output;
//you need to create another variable to store the previous number
// in order to be able to make the substraction
int originalNumber;

printf ("Please input your number\n");
scanf (" %i", &number);

while(number!=0)
{
originalNumber=number; // preserve the number in every loop
for (counter = 0; number >= 10; counter = counter +1)
{
// we changed the condition in the for loop in order to keep
// only inside the number the left most digit

number = number /10;

}
// the output will contain the left most digit in every loop
output=number;

while (counter > 0)
{
number = number * 10;
counter = counter - 1;
}
// we get the new value by doing the substraction
// 345= 2345 - 2000
number = originalNumber - number;

// print the new number for the next iteration
// and the left most digit
printf ("%i %i ", number, output);

//print the output using letters
switch(output)
{
case 0:
printf("Zero \n");
break;
case 1:
printf("One \n");
break;
case 2:
printf("Two \n");
break;
case 3:
printf("Three \n");
break;
case 4:
printf("Four \n");
break;
case 5:
printf("Five \n");
break;
case 6:
printf("Six \n");
break;
case 7:
printf("Seven \n");
break;
case 8:
printf("Eight \n");
break;
case 9:
printf("Nine \n");
break;
default:
break;
}
}

return 0;
}

现在,通过 swich() 语句用字母打印每个数字变得很容易!

您可以更改printf()的格式以获得所需的输出!!

关于c - 练习 5.6 Kochan 的 C 语言编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28030532/

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