不能隐式转换类型'double'& # 39; int # 39;.错误

本文关键字:int 错误 double 不能 转换 类型 | 更新日期: 2023-09-27 18:04:46

下面是一个尝试编写的c#代码来查找圆的面积

using System;
namespace DataTypeApplication 
{
    class Program 
    {
        static void Main(string[] args) 
        {
            double area;
            const double pi = 3.14;
            int side;
            Console.WriteLine("enter the radius of circle:");
            side = Convert.ToDouble(Console.ReadLine());
            area = (pi * side * side);
            Console.WriteLine("area is {}", area);
}
}
}

会在

这行出现错误

side = Convert.ToDouble(Console.ReadLine());

表示

不能隐式地将'double'类型转换为'int'类型。存在显式转换(您是否缺少强制类型转换?)

我做错了什么?

不能隐式转换类型'double'& # 39; int # 39;.错误

如果您将side变量的声明和赋值连接在一起

int side = Convert.ToDouble(Console.ReadLine());  

很容易看出,您将double类型的值赋给int类型的变量

考虑使用Int32。

使用TryParse方法安全地解析整数的字符串表示形式或将side声明为double

这里,我们从user获取一个值并将其转换为Double,使用这行代码Convert.ToDouble(Console.ReadLine());

现在你做错的是你将这个Double类型的值存储在INT类型的变量中,现在要纠正这个问题,你应该将变量'side'声明为

double side;

或使用

对输入值进行类型强制转换
side = (double) Convert.ToDouble(Console.ReadLine());
  /*  how to solve this problem
  Error   7   The type or namespace name 'CrystalDecisions' could not be 
  found 
  (are you missing a using directive or an assembly reference?)   
  C:'Users'ALI_COM'Documents'Visual Studio 
  2010'Projects'_database_pic'_database_pic'CrystalReport3.cs    14  11  
 _database_pic   */
// now i solved this Problem:
 **properties_> Target Framwork -> .NetFramwork 4**

转换为int:

int side = (int)Convert.ToDouble(Console.ReadLine())