Why does var x: Float = 4.5 Throws an Error? - kotlin

Anybody know why does my code throw an error everytime i assign a floating type variable?
I expect it not to throw any error

Add F at the end of your code otherwise it will think that you are trying to assign a double
var x: Float = 4.5F

4.5 is Double,
4.5f is Float.

Try this.
Method 1: Convert Float to Double.
var x: Double = 4.5
Method 2: Add f or F at the end.
var x: Float = 4.5f
or
var x: Float = 4.5F

Related

How to do multiple variable assignments in one line in Kotlin like C,C++?

I had to swap 2 numbers in one line expression using no other variable except x and y.
So I wrote the following .c program to swapp two numbers with the given conditions and it works like charm.
int main() {
int x =5, y =2;
x = y-x+(y=x);
printf("X=%d, y=%d", x, y);
return 0;
}
But when i try to do the same in kotlin it gives me an error that
Assignments are not expressions, and only expressions are allowed in
this context,
I can resolve this issue by introducing a third variable just like this. But I'm not allowed to have any other variable except x and y which are already given. So is there any other way I can do this in one line using any kotlin property?
Below is the kotlin program
fun main() {
var x = 5
var y = 10
x = y-x+(y=x)
println("X = $x, Y = $y")
}
While I have two suggestions below, I want to start with a recommendation against either of them, at least in this simple example.
It's usually a lot more clear to optimise code for developers to read in the following ways:
create an extra variable with a descriptive name
prefer val over var to avoid accidental mutations
and try to make the code 'linear', so the operations can be read from top-to-bottom without jumping between functions
avoid code that needs an IDE to see what the type-hints are
And I'll trust that the compiler will make make the code performant.
fun main() {
val x = 5
val y = 10
val newX = y
val newY = x
println("X = $newX, Y = $newY")
}
Local function
You could use a local function to perform the swap, as the function will still be able to access the original values.
fun main() {
var x = 5
var y = 10
fun swap(originalX: Int, originalY: Int) {
y = originalX
x = originalY
}
swap(x, y)
println("X = $x, Y = $y")
}
Scope function
This could be code-golfed into one line
use to to create a Pair<Int, Int>,
and a scope function to use the result.
fun main() {
var x = 5
var y = 10
(x to y).apply { x = second; y = first }
println("X = $x, Y = $y")
}
One line? Yes. More difficult to read? I think so.

Kotlin: Unexpected value for 2 Int multiplication

I've written a function to round a value in billion, here is my code:
private fun roundBillion(value: Double): Int {
val a = (value / 1000000).toInt()
val res = a * 1000000
return res
}
but when I execute the function I get an unexpected value in res variable. here is variables inspection when the break point is on return statement:
value = 1.7636265135946954E11
a = 176362
res = 268340864
I can't figure out where the problem is!
What you are experiencing is an integer overflow.
Double.MAX_VALUE is 1.7976931348623157E308.
Int.MAX_VALUE is 2147483647. Your number in the calculation (i.e. 176362000000) exceeds that.

Make "int" and "float" work in swift playground

so i am just starting to teach myself a bit ios and am an absolute amateur (please dont be too harsh and forgive questions, of which to you the answers might be obvious). so i wanted to get this following code to work:
var int bildBreite;
var float bildHoehe, bildFlaeche;
var bildBreite = 8;
var bildHoehe = 4.5;
var bildFlaeche = bildBreite * bildHoehe;
but get the mistakes as seen on this screenshot here (link: http://prntscr.com/6cdkvv )
concerning the screenshot: do not be confused with the "6" on the very right of line 10 , this was because before the "4.5" it was saying "6".
also, this is a xcode playground and the code i am trying out is from an objective c beginners guide, if that helps. (this whole swift and objective c mix is too confusing)
i would really appreciate an answer and if you have more questions to figure it out properly, i am happy to answer as quick as possible.
all the best
leo
Let's go over the code:
var int bildBreite;
var float bildHoehe, bildFlaeche;
You are trying to set the types of some variables in a non-Swift way. In order to declare variables of a specific type, you must add the type after the variable name: var bildBreite: Int Also note that class and struct names in Swift start with a capital letter, as #blacksquare noted.
var bildBreite = 8;
var bildHoehe = 4.5;
Here, it looks like you are trying to re-declare the variables. This isn't allowed.
var bildFlaeche = bildBreite * bildHoehe;
You are trying to multiply data between two different number types. This is not allowed in Swift. In order to actually do any math work, you would need to convert one to the same type as the other.
This version should work:
var bildBreite: Int;
var bildHoehe: Float;
var bildFlaeche: Float;
bildBreite = 8;
bildHoehe = 4.5;
bildFlaeche = Float(bildBreite) * bildHoehe;
The following code is a more concise version of your code:
// Inferred to be an Int
var bildBreite = 8
// This forces it to a Float, otherwise it would be a Double
var bildHoehe: Float = 4.5
// First, we convert bildBreite to a Float, then times it with Float bildHoehe.
// The answer is inferred to be a Float
var bildFlaeche = Float(bildBreite) * bildHoehe
int should be Int and float should be Float. Class and primitive names in Swift always begin with a capital letter.
To declare a variable in Swift, you do this:
var variableName: Int = intValue
Or you can let the compiler decide the type for you:
var variableNameA = 1
var variableNameB = 1.5
If you want to declare a variable and then assign it later you use an optional or an implicitly unwrapped optional:
var variableNameA: Int?
var variableNameB: Int!
variableNameA = 1
variableNameB = 2
var variableNameC = variableNameA! + variableNameB
As you can see from the last example, variableNameA is optional (meaning it can have a null value, so it must be unwrapped before usage using the ! operator; an implicitly unwrapped optional like variableNameB doesn't need to be unwrapped, but it's less safe and should be used with caution.
Note also that you only use var when you first declare a variable.
Good luck!
var bildBreite:Int = 8
var bildHoehe:Float = 4.5
var bildFlaeche:Float = bildBreite * bildHoehe
You dont need semi colons. You need to not try to apply java or any other language to this learn the syntax and you will be good

Inter-operability of Swift arrays with C?

How can one pass or copy the data in a C array, such as
float foo[1024];
, between C and Swift functions that use fixed size arrays, such as declared by
let foo = Float[](count: 1024, repeatedValue: 0.0)
?
I don't think this is easily possible. In the same way as you can't use C style arrays for parameters working with a NSArray.
All C arrays in Swift are represented by an UnsafePointer, e.g. UnsafePointer<Float>. Swift doesn't really know that the data are an array. If you want to convert them into a Swift array, you will have create a new object and copy the items there one by one.
let array: Array<Float> = [10.0, 50.0, 40.0]
// I am not sure if alloc(array.count) or alloc(array.count * sizeof(Float))
var cArray: UnsafePointer<Float> = UnsafePointer<Float>.alloc(array.count)
cArray.initializeFrom(array)
cArray.dealloc(array.count)
Edit
Just found a better solution, this could actually avoid copying.
let array: Array<Float> = [10.0, 50.0, 40.0]
// .withUnsafePointerToElements in Swift 2.x
array.withUnsafeBufferPointer() { (cArray: UnsafePointer<Float>) -> () in
// do something with the C array
}
As of Beta 5, one can just use pass &array
The following example passes 2 float arrays to a vDSP C function:
let logLen = 10
let len = Int(pow(2.0, Double(logLen)))
let setup : COpaquePointer = vDSP_create_fftsetup(vDSP_Length(logLen), FFTRadix(kFFTRadix2))
var myRealArray = [Float](count: len, repeatedValue: 0.0)
var myImagArray = [Float](count: len, repeatedValue: 0.0)
var cplxData = DSPSplitComplex(realp: &myRealArray, imagp: &myImagArray)
vDSP_fft_zip(setup, &cplxData, 1, vDSP_Length(logLen),FFTDirection(kFFTDirection_Forward))
The withUnsafePointerToElements() method was removed, now you can use the withUnsafeBufferPointer() instead, and use the baseAddress method in the block to achieve the point
let array: Array<Float> = [10.0, 50.0, 40.0]
array.withUnsafeBufferPointer { (cArray: UnsafePointer<Float>) -> () in
cArray.baseAddress
}
let's see what Apple do:
public struct float4 {
public var x: Float
public var y: Float
public var z: Float
public var w: Float
/// Initialize to the zero vector.
public init()
/// Initialize a vector with the specified elements.
public init(_ x: Float, _ y: Float, _ z: Float, _ w: Float)
/// Initialize a vector with the specified elements.
public init(x: Float, y: Float, z: Float, w: Float)
/// Initialize to a vector with all elements equal to `scalar`.
public init(_ scalar: Float)
/// Initialize to a vector with elements taken from `array`.
///
/// - Precondition: `array` must have exactly four elements.
public init(_ array: [Float])
/// Access individual elements of the vector via subscript.
public subscript(index: Int) -> Float
}

Round a float up to the next integer in objective C?

How can I round a float up to the next integer value in objective C?
1.1 -> 2
2.3 -> 3
3.4 -> 4
3.5 -> 4
3.6 -> 4
1.0000000001 -> 2
You want the ceiling function. Used like so:
float roundedup = ceil(otherfloat);
Use the ceil() function.
Someone did a little math in Objective C writeup here: http://webbuilders.wordpress.com/2009/04/01/objective-c-math/
Just could not comment Davids answer. His second answer won't work as modulo doesn't work on floating-point values. Shouldn't it look like
if (originalFloat - (int)originalFloat > 0) {
originalFloat += 1;
round = (int)originalFloat;
}
Roundup StringFloat remarks( this is not the best way to do it )
Language - Swift & Objective C | xCode - 9.1
What i did was convert string > float > ceil > int > Float > String
String Float 10.8 -> 11.0
String Float 10.4 -> 10.0
Swift
var AmountToCash1 = "7350.81079101"
AmountToCash1 = "\(Float(Int(ceil(Float(AmountToCash1)!))))"
print(AmountToCash1) // 7351.0
var AmountToCash2 = "7350.41079101"
AmountToCash2 = "\(Float(Int(ceil(Float(AmountToCash2)!))))"
print(AmountToCash2) // 7350.0
Objective C
NSString *AmountToCash1 = #"7350.81079101";
AmountToCash1 = [NSString stringWithFormat:#"%f",float(int(ceil(AmountToCash1.floatValue)))];
OR you can make a custom function like so
Swift
func roundupFloatString(value:String)->String{
var result = ""
result = "\(Float(Int(ceil(Float(value)!))))"
return result
}
Called it like So
AmountToCash = self.roundupFloatString(value: AmountToCash)
Objective C
-(NSString*)roundupFloatString:(NSString *)value{
NSString *result = #"";
result = [NSString stringWithFormat:#"%f",float(int(ceil(value.floatValue)))];
return result;
}
Called it like So
AmountToCash = [self roundupFloatString:AmountToCash];
Good Luck! and Welcome! Support My answer!