简单的用sprintf体 - c [英] Simple use of sprintf - C

查看:117
本文介绍了简单的用sprintf体 - c的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出为什么一个更大的问题正在发生,使用更小的程序为例。这个小程序不能正常工作,导致我相信这是我认为是有缺陷的功能的理解。

据我(有)认为,下面的程序应该初始化字符串,最多30个字符,然后取数5九显著的数字,并把它变成该字符串。然后程序应该打印值5.00000000。但是,程序打印值7.96788(...)。这是为什么?

 的#include<&stdio.h中GT;诠释的main()
{
CHAR字[30];
sprintf的(字,%9克,5);
的printf(字);
返回0;
}


解决方案

这是因为 5 是一个整数( INT ),和你告诉的sprintf 来pretend,这是一个双precision浮点数()。您需要更改如下:

  sprintf的(字,%9克,5);

要么这些:

  sprintf的(字,%9克,5.0);
sprintf的(字,%9克(双)5);

I'm trying to work out why a larger problem is occuring, using a smaller program as an example. This smaller program does not work, leading me to believe it is my understanding of the function that is flawed.

As far as I (had) believed, the following program should initialise a string with up to 30 characters, then take the number '5' to nine significant figures, and turn it into that string. The program should then print the value '5.00000000'. However, the program prints the value 7.96788(...). Why is this?

#include <stdio.h>

int main()
{
char word[30];
sprintf(word,"%.9g", 5);
printf(word);
return 0;
}

解决方案

This is because 5 is an integer (int), and you're telling sprintf to pretend that it's a double-precision floating-point number (double). You need to change this:

sprintf(word,"%.9g", 5);

to either of these:

sprintf(word,"%.9g", 5.0);
sprintf(word,"%.9g", (double) 5);

这篇关于简单的用sprintf体 - c的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆