arcend
arcend

Reputation: 1

What's wrong with my c++ code? for a = 90 Z should be equal to -1, but I'm getting completly different answer. Why?

I tried to make code that can calculate trigonometric function but it went wrong and i don't know what to do because I just can't see any mistakes

using namespace std;
#define _CRT_SECURE_NO_WARNINGS
#define _USE_MATH_DEFINES
#include <iostream>
#include <conio.h>
#include <cmath>

int main()
{`

    const double pi = M_PI;
    double Z, a, sin1, cos1, X, Y;

    //printf("Input a =");
    printf("%s", "Input a = ");
    scanf("%g", &a);
    a = a * pi / 180;
    sin1 = sin(3 * pi - 2 * a);
    X = (sin1 * sin1)*2;
    cos1 = cos(5 * pi - 2 * a);
    Y = cos1 * cos1;
    Z = X - Y;
    printf("Z = %g\n\n", Z);

    _getch();
    return 0;


}`

Upvotes: 0

Views: 71

Answers (1)

As mentioned in the above commments, enabling compiler warning messages should indicate the problem and suggest a solution, thus removing _CRT_SECURE_NO_WARNINGS may help to view the problem and solution:

(15,11): warning C4477: 'scanf' : format string '%g' requires an argument of type 'float *', but variadic argument 1 has type 'double *'
(15,11): message : consider using '%lg' in the format string
(15,5): error C4996: 'scanf': This function or variable may be unsafe. Consider using scanf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

When using the compiler suggestion:

scanf("%lg", &a);

as also mentioned in the above comments, we still get a warning regarding use of scanf:

(15,5): error C4996: 'scanf': This function or variable may be unsafe. Consider using scanf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

So, to keep using scanf when we include _CRT_SECURE_NO_WARNINGS and get expected output, however using the compiler suggested scanf_s (and remove _CRT_SECURE_NO_WARNINGS) also produces expected output.

However, since you've included iostream, c++ provides the cin object of class iostream, thus the simplest solution may be to use cin as suggested in the above comment.

Upvotes: 1

Related Questions