2
#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). Later I am converting this into string by integer to ASCII function. I have problem to divide that number by 10.

Clifford
  • 88,407
  • 13
  • 85
  • 165

5 Answers5

2

you need to use a float variable to get floating point results.

try

float num = 255;
num = num / 10;
motz
  • 103
  • 1
  • 6
1

When storing a floating value to an integer the decimal part is thrown away. So in num = num / 10; num will be 25 because it is an int.

Thomas Kaliakos
  • 3,274
  • 4
  • 25
  • 39
1

An integer divided by an integer is an integer, so you get 25 as a result. 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. You might also want to specify a width and precision (see printf).

If you really need a string buffer, you can use sprintf to write the result to a buffer.

#include<stdio.h>
int main()
{
    float num = 255f;
    num = num / 10;
    printf("%f\n", num);
    return 0.
}
Werner Henze
  • 16,404
  • 12
  • 44
  • 69
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);
}
JBL
  • 12,588
  • 4
  • 53
  • 84
0

Firstly, num is (as pointed out) an integer, so cannot take fractional values.

Secondly, itoa is not standard. You should use snprintf (which is not only standard, it is not susceptible to buffer overflows).

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.

Tom Tanner
  • 9,244
  • 3
  • 33
  • 61