Kai McClymont
Kai McClymont

Reputation: 55

C# Illusive Maths issue

I am writing a program to calculate the amount of turf needed for a garden with a one meter border, and then find the total cost if the turf costs £10 per sq meter. This is the code I have so far:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _3._6
{
    public partial class frmTurfCalculator : Form
    {
        public frmTurfCalculator()
        {
            InitializeComponent();
        }

        public float LengthFinal { get; private set; }
        public double Lengthvalue { get; private set; }
        public float WidthFinal { get; private set; }
        public double WidthValue { get; private set; }

        private void btnCalculate_Click(object sender, EventArgs e)
        {
            Lengthvalue = Convert.ToDouble(txtLength.Text);
            double LengthFinal = (Lengthvalue - 2);

            WidthValue = Convert.ToDouble(txtWidth.Text);
            double WidthFinal = (WidthValue - 2);

            double GardenArea = (WidthFinal * LengthFinal);
            double TurfCost = (10 * GardenArea);
            lblOutput1.Text = ("Amount of Turf (with 1m boundry): " + GardenArea);
            lblOutput2.Text = ("Total cost of turf = " + TurfCost + "£");
        }
    }
}

For some reason, whenever I run the (I used Width of 6m and Length of 6m) it comes up with a really weird result (16meters squared). This happens with different inputs, but for the sake of explanation I'm using 6m.

Thanks

Upvotes: 0

Views: 86

Answers (2)

David Watts
David Watts

Reputation: 2289

I don't believe you have an issue. You state:

I am writing a program to calculate the amount of turf needed for a garden with a one meter border

The values you are using for width and height are both 6. So you have a 6 * 6 garden, with a 1 meter border (Assuming the border surrounds all sides of the turf). That leaves you with a 4*4 area that needs turfing.

This leaves you with a remaining area to turf of 16 meters squared, which is the result you are getting. So the final value should be £160.

Upvotes: 2

user1666620
user1666620

Reputation: 4808

Your problem is with these 2 lines of code:

double LengthFinal = (Lengthvalue - 2);

double WidthFinal = (WidthValue - 2);

You are subtracting 2 from width and length. So 6 * 6 becomes 4 * 4, giving you the result of 16.

If you set breakpoints and debugged through your code (or even just looked at your code), you would have seen this immediately.

Upvotes: 2

Related Questions