我是C语言的新手。请帮帮我。 我正在编写一个程序,它接受十进制数并遍历它们以找到数字之和。
例如,233.1234是输入 sum = 18是输出
谢谢
到目前为止我的代码
void main()
{
float num;
printf("Enter the decimal number : ");
scanf("%d",&num);
printf("%10.10d",num);
}
打印0000000000 谁能告诉我怎么打印? 谢谢
答案 0 :(得分:1)
#include <stdio.h>
#include <stdlib.h>
int main(){
double num;
char input[32], *p;
printf("Enter the decimal number : ");
fgets(input, sizeof input, stdin);
num = strtod(input, &p);
if(*p=='\n'){
int n, sum = 0;
printf("input : %s", input);
for(p = input; *p ; ++p){
if(1==sscanf(p, "%1d", &n))
sum += n;
}
printf("sum = %d\n", sum);
} else {
printf("Invalid input!\n");
}
return 0;
}
答案 1 :(得分:0)
Following is the program
#include<stdio.h>
main()
{
//float f = 233.1234;
float f;
float s;
int x;
int unit = 0;
printf("Enter the decimal number \n");
scanf("%f",&f);
printf("Entered the decimal number =%f\n",f);
s = f;
while((int)s % 10) {
s = s*10;
}
x = (int) s/10;
printf("x=%d,s=%f \n",x,s);
while(x % 10) {
unit = unit + (x % 10);
x = x / 10;
}
printf("Sum of the digit = %d \n",unit);
}
// output in the terminal
Enter the decimal number
233.1234
Entered the decimal number =233.123398
x=2331234,s=23312340.000000
Sum of the digit = 18