Error CS0266: Cannot implicitly convert type `double' to `int'. An explicit conversion exists (are you missing a cast?)

I am trying to find the area of a circle, but only to a few decimals (3.14 is all i really need). Anyway i get this error once i made the script and my research hasnt found an answer. Im fairly new to C# so i dont understand many complex functions. here is the error

error CS0266: Cannot implicitly convert type double' to int’. An explicit conversion exists (are you missing a cast?)

Here is the script

using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System;

public class Calculations : MonoBehaviour {
	
	public GameObject textField_1;
	public GameObject textField_2;
	public GameObject textField_3;
	public Text Result;
	InputField t1;
	InputField t2;
	InputField t3;

	void Start()
	{
		t1 = textField_1.GetComponent<InputField> ();
		t2 = textField_2.GetComponent<InputField> ();
		t3 = textField_3.GetComponent<InputField> ();
	}

	
	public void Product() {
		int a = Convert.ToInt32(t1.text);
		int b = Convert.ToInt32(t2.text);
		int c = Convert.ToInt32 (t3.text);
		int d = a / 2;
		int e = (3.14159 * d) * (3.14159 * d); 
		Result.text = d.ToString ();
	}
	
}

You are trying to convert type double to int, as your error message say it’s really that simple.

I can’t tell you exactly where as you didn’t include the line from the console error message, but I’m pretty sure that this line is the problem as it seems like the user can decide the value of a(?)

int d = a / 2;

You can’t divide int by int and make it an int if the output will become a double, for example;

  • 10/5 = 2 (this is okay, 2 is int).
  • 10/0.1337 = 74,79 (this is not an int, this is a double so you can’t make it an int).

You can solve this by obviosly change the variable to a double, or you can use MathF.RoundToInt(); if you cast the value to a float;

int d = MathF.RoundToInt((float)(a / 2));

I hope this helps, if not let me know and I’ll try to further assist your issue.

EDIT:

I overlooked this line that you got;

int e = (3.14159 * d) * (3.14159 * d); 

You can’t use this line, that makes no sense. You my friend need to read more about the different variable types to learn how this works.

I STRONGLY advise you to watch BOTH of these short clips on C#, I know the audio suck but this guy is amazing. I in fact advice you to watch pretty much the entire playlist, at least around the first 50 is mandatory stuff, good luck :slight_smile:

C# Beginners Tutorial - 4 - Variables

C# Beginners Tutorial - 35 - More Variable Types

C# Beginners Tutorials Playlist

The variable int only stores numbers without a comma. Like 1; 6; 373… Double stores numbers with comma. Like 1.234; 4.976.
Change the type of d and e to double.