简体   繁体   English

指导我将数字除以10,然后转换为字符串

[英]guide me in dividing the number by 10 and later converting into a string

#include<stdio.h>
int main()
{
int num = 255;
num = num / 10;
char buf[5];
itoa(num, buf,10);
printf("%s", buf);
return 0.
}

I am trying to divide the integer number by 10 but I am getting a solution of 25 ( I should get 25.5). 我正在尝试将整数除以10,但得到的解决方案是25(我应该得到25.5)。 Later I am converting this into string by integer to ASCII function. 稍后,我将其转换为整数并转换为ASCII函数的字符串。 I have problem to divide that number by 10. 我很难将那个数字除以10。

you need to use a float variable to get floating point results. 您需要使用float变量来获取浮点结果。

try 尝试

float num = 255;
num = num / 10;

When storing a floating value to an integer the decimal part is thrown away. 将浮点值存储为整数时,小数部分将被丢弃。 So in num = num / 10; 因此,以num = num / 10; num will be 25 because it is an int. num将为25,因为它是一个int。

An integer divided by an integer is an integer, so you get 25 as a result. 整数除以整数就是整数,因此结果为25。 You need to cast divisor or denominator to float or double first. 您需要将除数或分母强制转换为浮点型或双精度型。

To output a float to console you can use printf with %f , %F , %e , %E , %g or %G format string. 要将float输出到控制台,可以将printf%f%F%e%E%g%G格式字符串一起使用。 You might also want to specify a width and precision (see printf ). 您可能还需要指定宽度和精度(请参见printf )。

If you really need a string buffer, you can use sprintf to write the result to a buffer. 如果确实需要字符串缓冲区,则可以使用sprintf将结果写入缓冲区。

#include<stdio.h>
int main()
{
    float num = 255f;
    num = num / 10;
    printf("%f\n", num);
    return 0.
}
#include <stdio.h>
#include <string.h>

char buffer[20];

void main() {
    float num = 255;
    num = num / 10;

    sprintf(buffer, "%g", num );

    printf("%s",buffer);
}

Firstly, num is (as pointed out) an integer, so cannot take fractional values. 首先,num是(如所指出的)整数,因此不能采用小数。

Secondly, itoa is not standard. 其次,itoa不是标准的。 You should use snprintf (which is not only standard, it is not susceptible to buffer overflows). 您应该使用snprintf(这不仅是标准的,而且不容易受到缓冲区溢出的影响)。

So: 所以:

#include <stdio.h>

int main()
{
    float num = 255;
    num = num / 10;

    char buf[5];
    snprintf(buf, sizeof(buf), "%g", num);
    printf("%s", buf);
    return 0.
}

will do what you want. 会做你想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM