在C ++中不输出尾随零 [英] Do Not Output Trailing Zeroes in C++
本文介绍了在C ++中不输出尾随零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果结果是整数,则不输出小数点.
If the result is an integer, do not output the decimal point.
如果结果是浮点数,则不要输出任何尾随零.
If the result is a floating point number, do not output any trailing zeroes.
如何在 c
或 c ++
中进行操作:
double result;
/*some operations on result */
printf("%g", result);
以上方法正确吗?在我的情况下,我没有得到正确的答案.
Is the above approach correct? I'm not getting the correct answer with in my situation.
推荐答案
您可以使用 snprintf
将double值打印到char数组中,然后从头到头,替换为'0'加上'\ 0',最后得到一个没有尾部零的数字.这是我的简单代码.
you can use snprintf
to print the double value into a char array, then from the end to the head, replace the '0' with '\0', finally you get a the number without tailling zeroes.Here is my simple code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void
remove_zeroes(double number, char * result, int buf_len)
{
char * pos;
int len;
snprintf(result, buf_len, "%lf", number);
len = strlen(result);
pos = result + len - 1;
#if 0
/* according to Jon Cage suggestion, removing this part */
while(*div != '.')
div++;
#endif
while(*pos == '0')
*pos-- = '\0';
if(*pos == '.')
*pos = '\0';
}
int
main(void)
{
double a;
char test[81];
a = 10.1;
printf("before it is %lf\n", a);
remove_zeroes(a, test, 81);
printf("after it is %s\n", test);
a = 100;
printf("before it is %lf\n", a);
remove_zeroes(a, test, 81);
printf("after it is %s\n", test);
return 0;
}
输出为
before it is 10.100000
after it is 10.1
before it is 100.000000
after it is 100
这篇关于在C ++中不输出尾随零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文