0

When testing out the equation I get a -1.#IND00 as an answer when it solves for y. I'm basically trying to create a program that solves for y give the equation below

y=y/(3/17)-z+x/(a%2)+PI

#include <stdio.h> 
#include <math.h>
#define PI 3.14

int main (void)
{
    int a=0;
    double z=0,x=0,y=0;

    printf("Values for x, z, and a:"); 
    scanf("%lf%lf%d", &x,&z,&a); 

    y = (((y/(double)(3/17)))-z + (x/(a%2))+PI); 
    printf("y = %lf\n", y);

    return 0;
}
Csisis
  • 1
  • 11
    The cast in `(double)(3/17)` is too late to change anything. You want to cast before the division - or just write `3.0`. – T.C. Sep 11 '14 at 05:18
  • as @T.C. said the double cast is too late. also consider using `static_cast` over C-style casts. also check the return value of `scanf` to ensure you have read 3 valid values – Zaiborg Sep 11 '14 at 06:15
  • 1
    That doesn't solve the equation for `y`, it just assigns a value to `y`. If you fix the division by zero, the value will be `-z + (x/(a%2))+PI`. You're going to have to solve the equation yourself first. – molbdnilo Sep 11 '14 at 06:17

1 Answers1

0

Since there are no questionmarks, I assume the question is "How do you write a C++ program that solves this equation?"

C++ is a programming language and by itself is not able to solve your equation, i.e. C++ won't do any transformation to your equation to get it into a form where y occurs only on the lefthand side and all parameters on the righthand side. You have to transform it yourself, manually or by using a solver.

What happens in the posted code?

Lets start at the leftmost part of the equation y/(double)(3/17) from inside out according to the parentheses:

  • 3/17 is interpreted as integer division, which results in 0;
  • (double)(0) casts the integer 0 into a double of 0.0;
  • y/0.0 is a division by 0 as explained in this post which results in your error.

You could fix this as pointed out in the comments by either casting the first integer like (double)3/17 or turning the integer 3 into a double 3.0 or using static_cast.

  • However, y is still initialized to 0, so y/(double)3/17 is 0 and the equation calculated is basically -z + x/(a%2) + PI.

So, unless you transform the equation and put the transformed equation into the code, you won't get the results you expect.

Community
  • 1
  • 1
user3141592
  • 121
  • 1
  • 10