Search code examples
ctypesfloating-pointcodeblocksturbo-c

c code doesnt work on turbo c++ with the float numbers


#include <stdio.h>
#include <math.h>

int main(void)
{
    double r,d,x,y,pi;

    clrscr();
    printf("Input the value of r and degree: ");
    //scanf("%f",&r);
    //scanf("%f",&d);

    r = 12;
    d = 195;
    pi = 3.14;
    x = r * cos(d * pi/180);
    y = r * sin(d * pi/180);

    printf("The polar form is: (%f,%f)", x, y);
    getch();
}

In the 1st case with defined values of r and d the output comes correct but in 2nd case when I give the input the output doesn't match with the original answer. The code worked on codeblocks but isn't working on turbo c++.

what am I doing wrong in turbo c++?


Solution

  • Mis-matched format specifier. Use "%lf" with a double *

    double r,d,x,y,pi;
    ...
    //scanf("%f",&r);
    //scanf("%f",&d);
    scanf("%lf",&r);
    scanf("%lf",&d);
    

    Better codes checks for success before using r.

    if (scanf("%lf",&r) != 1) Handle_Error();
    

    Output is Cartesian coordinates. @Jens. I'd also recommend a '\n'.

    // printf("The polar form is: (%f,%f)", x, y);
    printf("The Cartesian form is: (%f,%f)\n", x, y);
    

    It appears Turbo-C requires "l" when printing double, so use

    printf("The Cartesian form is: (%lf,%lf)\n", x, y);
    

    Little reason to use a low precision pi. Suggest

    pi = acos(-1.0);