Ahmed Faizan - 5 months ago 37

C# Question

I am trying to predict tide in c# using a formula given below:

The program was already done in excel, however when translating it to c# I am encountering some problems.

This is the formula in excel:

`=PI()*((C18)/(C19)+1)`

Cells C18 and C19 just contain subtraction of two date cells each

In C# I am having trouble finding A.

There are 2 problematic areas in finding A.

`(t - t1)/(t2 - t1)`

Here is my code:

`DateTime t = new DateTime(2016, 6, 21, 13, 41, 00);`

DateTime t1 = new DateTime(2016, 6, 21, 7, 13, 00);

DateTime t2 = new DateTime(2016, 6, 21, 13, 57, 00);

double h1 = 1.421;

double h2 = 2.337;

double h2_minus_h1 = h2 - h1;

TimeSpan t_minus_t1 = TimeSpan.FromTicks(t.Subtract(t1).Ticks);

TimeSpan t2_minus_t1 = TimeSpan.FromTicks(t2.Subtract(t1).Ticks);

TimeSpan MainCalculationForA = TimeSpan.FromTicks((t.Subtract(t1).Ticks) / (t2.Subtract(t1).Ticks));

MessageBox.Show(MainCalculationForA.ToString());

The answer for this which is

`(t - t1)/(t2 - t1)`

`00:00:00`

Note:The formula is taken from here

tide prediction pdf

note:

`(t - t1)`

`(t2 - t1)`

Answer

From the PDF provided, `t`

, `t1`

and `t2`

are in **decimal hours**, so you need `.TotalHours`

instead

```
DateTime t = new DateTime(2016, 6, 21, 13, 41, 00);
DateTime t1 = new DateTime(2016, 6, 21, 7, 13, 00);
DateTime t2 = new DateTime(2016, 6, 21, 13, 57, 00);
double h1 = 1.421;
double h2 = 2.337;
double t_min_t1 = (t - t1).TotalHours;
double t2_min_t1 = (t2 - t1).TotalHours;
double A = Math.PI*(t_min_t1/t2_min_t1 + 1);
double h = h1 + (h2 - h1)*((Math.Cos(A) + 1)/2);
MessageBox.Show(h.ToString());
```

The end result is `2.33345960154238`

.