How to Convert Integer into a String then turn it to Floating point?

[B]Good day everyone,[/B]

Hope you could help me on this one

The program is running but the result is far from what I want please help me... TIA

Like this one:

[B]Input:[/B]
------------------------------------
Enter first number: 7
Enter second number: 45
------------------------------------

[B]
Output:[/B]
------------------------------------
7.45
[B]7.00[/B]
------------------------------------


[B]which should be my target output is:[/B]
------------------------------------
7.45
[B]7.45[/B]
------------------------------------

[CODE]
#include
#include
#include
main()
{
char str1[80],str2[80];
int num1, num2;
float num3;

clrscr();

printf("Enter first number: ");
scanf("%d",&num1);
printf("Enter second number: ");
scanf("%d",&num2);

sprintf(str1,"%d.",num1);
sprintf(str2,"%d",num2);

strcat(str1,str2);
printf("%s
",str1);

num3 = atoi(str1);
printf("%.2f",num3);

getch();
}
[/CODE]

[B]Thanks in advanced again![/B]:)

Comments

  • num3 = atoi(str1);

    atoi will truncate your float to an integer first. if you want/need a float, use atof.

    [code]
    printf("Enter first number: ");
    scanf("%d",&num1);
    printf("Enter second number: ");
    scanf("%d",&num2);

    sprintf(str1, "%d.%d", num1, num2);
    sscanf(str1, "%f", &num3);

    printf("%.2f", num3);
    [/code]

    another way to more or less do the same thing
  • [b]Thanks for your kind reply Sir!
    Problem Solved! God Bless!!![/b]
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories