gpt4 book ai didi

c - 如何从C中的数字中提取数字?从最高位开始?

转载 作者:太空宇宙 更新时间:2023-11-04 00:24:46 24 4
gpt4 key购买 nike

在 C 中从最低有效位开始的数字中获取数字非常容易:

#include <stdio.h>

int main()
{
int num = 1024;

while(num != 0)
{
int digit = num % 10;
num = num / 10;
printf("%d\n", digit);
}


return 0;
}

但是如何从第一个数字(此处为 1)开始提取数字,以便该解决方案可以应用于任何数字?

用数组会很简单,但我不想使用数组,也不想使用逻辑运算符。

最佳答案

下面的程序做你想做的:

#include <stdio.h>

int main()
{

int num =0;
int power=1;

printf("Enter any number:");
scanf("%d",&num);

while(num>power)
power*=10;

power/=10;

while(num != 0)
{
int digit = num /power;
printf("%d\n", digit);
if(digit!=0)
num=num-digit*power;
if(power!=1)
power/=10;
}



return 0;
}

关于c - 如何从C中的数字中提取数字?从最高位开始?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26688413/

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