+ 1

Convert.ToInt32 vs Convert.ToDouble

So I was working throught the C# course and trying to find the area of a circle test, and kept getting stuck on the second test run where it used 6.4. Here is my original code: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoloLearn { class Program { static void Main(string[] args) { const double pi = 3.14; double radius = Convert.ToInt32(Console.ReadLine()); double radiusSquare = Convert.ToInt32(radius*radius); Console.WriteLine(radiusSquare*pi); //your code goes here } } } In this I kept using Convert.ToInt32, and then learned that I needed to use Convert.ToDouble. What exactly is the difference between the two? I was under the impression from the lessons that convert.Toint32 was like converting to decimals, and kept getting confused as to why it kept failing. With this, how exactly does the Convert.ToThing command work?

3rd Jan 2022, 5:28 AM
Jack Berberette
3 Respuestas
+ 6
Jack Berberette Convert.ToInt32 is used to convert input in integer Convert.ToDouble is used to convert input in double. Why we need to convert because when we take input it is considered as String so 6 or 6.4 will be considered as String. As radius of circle might be in decimal so we need to convert input in double. So here double radius = Convert.ToDouble(Console.ReadLine()); Now area is double area = pi * radius * radius; Or you can use Math.Pow like this: double area = pi * Math.Pow(radius, 2); Remember 6.4 is a double value but when you take input then it is considered as string so directly converting in int will give you error.
3rd Jan 2022, 6:26 AM
A͢J
A͢J - avatar
0
I appreciate the answers, thank y'all!
3rd Jan 2022, 10:28 PM
Jack Berberette