Integer division in Dart - type 'double' is not a subtype of type 'int'

前端 未结 3 1176
孤街浪徒
孤街浪徒 2020-12-16 09:54

I have trouble with integer division in Dart as it gives me error: \'Breaking on exception: type \'double\' is not a subtype of type \'int\' of \'c\'.\'

Her

相关标签:
3条回答
  • 2020-12-16 10:09

    Integer division is

    c = a ~/ b;
    

    you could also use

    c = (a / b).floor();
    c = (a / b).ceil();
    

    if you want to define how fractions should be handled.

    0 讨论(0)
  • 2020-12-16 10:12

    That is because Dart uses double to represent all numbers in dart2js. You can get interesting results, if you play with that:

    Code:

    int a = 1; 
    a is int; 
    a is double;
    

    Result:

    true
    true
    

    Actually, it is recommended to use type num when it comes to numbers, unless you have strong reasons to make it int (in for loop, for example). If you want to keep using int, use truncating division like this:

    int a = 500;
    int b = 250;
    int c;
    
    c = a ~/ b;
    

    Otherwise, I would recommend to utilize num type.

    0 讨论(0)
  • 2020-12-16 10:36

    Short Answer

    Use c = a ~/ b.

    Long Answer

    According to the docs, int are numbers without a decimal point, while double are numbers with a decimal point.

    Both double and int are subtypes of num.

    When two integers are divided using the / operator, the result is evaluated into a double. And the c variable was initialized as an integer. There are at least two things you can do:

    1. Use c = a ~/ b.

    The ~/ operator returns an int.

    1. Use var c;. This creates a dynamic variable that can be assigned to any type, including a double and int and String etc.
    0 讨论(0)
提交回复
热议问题