本文介绍了打印小数位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
希望单独打印一个小数位,并且在不使用类型转换的情况下,有多少小数位于浮点数中。
例如:你应该在ur pgm中有这个语句:float f = 345.876;
然后输出应该是
o / p:8 7 6和3
我需要的算法适用于所有浮点数
want to print a fractional digits seperately and how many fractionals are in floating point numbers without using typecast..
eg: u should have this statement in ur pgm : float f=345.876;
then output should be
o/p:8 7 6 and 3
the algorithm i need which is working for all floating numbers
推荐答案
#include <stdio.h>
#include <string.h>
int main()
{
char result[128];
char buffer[128];
float f = 345.876f;
sprintf(buffer,"%f",f);
int count = 0;
int r = 0;
int found_point = 0;
for(int i = 0; i < 128 && buffer[i] != 0; ++i) {
if (found_point) {
result[r] = buffer[i];
result[++r] = ' ';
result[++r] = 0;
++count;
}
else {
found_point = buffer[i] == '.' ? 1 : 0;
}
}
if (count > 0) {
strcpy(result + r, "and ");
char c_buffer[128];
sprintf(c_buffer, "%d", count);
strcpy(result + strlen(result), c_buffer);
}
printf("o/p: %s\r\n", result);
return 0;
}
希望这会有所帮助,
Fredrik
Hope this helps,
Fredrik
这篇关于打印小数位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!