Question

I'm trying to get a simple result on a console app in C#

Console.Write("Enter a number: ");
double x = Convert.ToDouble(Console.ReadLine());
x=(7*x/4+1/2) - (5*x/4+1/2)*Math.Acos(Math.PI*x);
Console.WriteLine(x);

This is resulting in NaN, and I can't figure out why. I'm not very programming savvy, so I'm sure its something obvious. Thanks!


EDIT: It should have been Math.Cos, not Math.Acos. Now I have come across something else, when I input say x=3, it returns a result of 9; however, it should result in 10. Any reason as to why?

Was it helpful?

Solution 2

You're using Math.Acos, which can only take inputs between -1 and +1. When you put in Pi, it returns NaN, which then breaks the whole formula. You probably wanted simply Math.Cos

EDIT

On getting the wrong answer, it's probably integer division on the 1/2. When dividing integers, the answer is truncated, so 1/2 results in 0, not the expected 0.5, thus giving you an answer off by 1. Try it with 1.0/2.0

OTHER TIPS

Start by splitting it up. once you get a NaN, all math after that is a NaN!

You have to check for NaN using isNaN, because x == NaN is always false!

As good practice, you should also check that the text input by the user is actually a number. You can use double.TryParse, which returns false if the text cannot be parsed as a number. Your current code will throw an exception instead

Arccos pi = "the angle whose cosine is pi". Cosines are only ever in the range -1 to +1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top