I tried to print out:
F degrees Fahrenheit = C degrees Celsius
and I can't get it to work I have tried so many things also be nice I'm new to coding.
fun main(args: Array<String>) {
var F = "32";
var C = (F - 32) * .5555556;
var conversion = "F degrees Fahrenheit = C degrees Celsius"
println(conversion);
}
You can use a template string:
fun main() {
var f = 68.0;
var c = (f - 32.0) * 5.0 / 9.0;
var conversion = "$f degrees Fahrenheit = $c degrees Celsius"
println(conversion)
}
Other things to note:
I've used a floating point number instead of a string for the f variable. This allows me to use floating point math to calculate the Celsius equivalent.
I renamed the variables to be lowercase, as per the coding conventions.
I replaced the .5555556 literal with 5.0 / 9.0. Better to introduce rounding errors later rather than earlier.
Even though in this case it's sufficient to only explicitly turn the f variable into a floating point number to force floating point math to be used, it's probably safer to just apply the same logic to all numbers.
Related
I have a Vec2 class in kotlin.
I overloaded the operator * like this:
operator fun times(v:Float): Vec2 {
return Vec2(this.x * v, this.y * v)
}
End the behavior is just as I expected, I can use * and *= to scale the vector
var a = Vec2() * 7f; a *= 2f
However, from my understanding what I do here, is I create a new object, by calling Vec2(), every time I use *
Even if I use *= and I do not really need to return anything, as I could just edit the object itself (using this keyword)
Is there any way to overload the *= operator, so that it has the similar behavior to this function?
fun mul(v:Float) {
this.x *= v; this.y *= v
}
I need my application to run smoothly, and these operators are used quite a lot,
I do not want any lags caused by garbage collector's work.
There is no need to create a new object, you should just change your x and y to var's so they become reassignable.
Doing this will most likely end you up with something like this:
class Vec2(var x: Float, var y: Float) {
operator fun times(v: Float) {
x *= v
y *= v
}
}
Then in your implementation it is as simple as:
val a = Vec2(1.0f, 1.0f)
a * 2f
// After this line both x and y are 2.0f
If you really want to overload the *= operator then add the timesAssign operator function instead for more info see the kotlin docs
What should I write in the place of area.toFixed(2)
fun main(args: Array<String>) {
val a = 20
val h = 30
val area = a * h / 2
println("Triangle area = ${area.toFixed(2)}")
}
I think you really meet a problem that how to convert Javascript code to Kotlin code. You need to ask the question clearly at next time, :). you can use String#format instead, for example:
println("%.2f".format(1.0)) // print "1.00"
println("%.2f".format(1.253)) // print "1.25"
println("%.2f".format(1.255)) // print "1.26"
AND the area is an Int which means it will truncates the precision, Kotlin doesn't like as Javascript use the numeric by default, so you should let a*h divide by a Double, then your code is like as below:
// v--- use a `Double` instead
val area = a * h / 2.0
println("Triangle area = ${"%.2f".format(area)}")
How can I make it in kotlin using for loop?
for (double i = 0; i < 10.0; i += 0.25) {
System.out.println("value is:" + i);
}
You should use the Intellij plugin for converting Java code for Kotlin. It's pretty neat (unless you have complex code using lambdas) This is what it converts to for your given question:
var i = 0.0
while (i < 10.0) {
println("value is:" + i)
i += 0.25
}
Here is the kotlin code equivalent to for loop.
var i = 0.0
while (i < 10.0)
{
println("value is:" + i)
i += 1.0
}
Kotlin for loop only support iterate the arrays.Please refer https://kotlinlang.org/docs/reference/control-flow.html
It's achievable in different way
var length:Double = 10.0
var increment:Double = 0.25
for (index in Array((length/increment).toInt(), { i -> (i * increment) }))
println(index)
I'm not sure if this syntax is new, but natural numbers may be used to iterate values like so.
(0..(10*4)).map {
it / 4.0 as Double
}.forEach {
println(it)
}
I'm avoiding iteration on IEEE 754 floating points, as that could potentially cause errors. It may be fine in this case, but the same may not be true depending on environment, context, and language. It's best to avoid using floating point except in cases where the numbers are expected to have arbitrary precision, i.e. uses real numbers or continuity.
This syntax may be used within a for loop as well if you don't need to store the result. However, for loops should be avoided for the most part if you want immutability (which you should).
for (i in 0..10) {
println("Project Loom is a lie! $i")
}
I am implementing the CORDIC algorithm for the sin trigonometric function. In order to do this, I need to hardcode/calculate a bunch of arctangent values. Right now my function seems to work (as validated by Wolfram Alpha) to the precision that is printed, but I would like to be able to print all 32 bits of precision of my f32. How may I do that?
fn generate_table() {
let pi: f32 = 3.1415926536897932384626;
let k1: f32 = 0.6072529350088812561694; // 1/k
let num_bits: uint = 32;
let num_elms: uint = num_bits;
let mul: uint = 1 << (num_bits - 2);
println!("Cordic sin in rust");
println!("num bits {}", num_bits);
println!("pi is {}", pi);
println!("k1 is {}", k1);
let shift: f32 = 2.0;
for ii in range(0, num_bits) {
let ipow: f32 = 1.0 / shift.powi(ii as i32);
let cur: f32 = ipow.atan();
println!("table values {}", cur);
}
}
Use the precision format specifier; a . followed by the number of decimal points of precision you'd like to see:
fn main() {
let pi: f32 = 3.1415926536897932384626;
let k1: f32 = 0.6072529350088812561694; // 1/k
println!("pi is {:.32}", pi);
println!("k1 is {:.32}", k1);
}
I chose 32, which is more than the number of decimal points in either of these f32s.
pi is 3.14159274101257324218750000000000
k1 is 0.60725295543670654296875000000000
Note that the values no longer match up; floating point values are difficult! As mentioned in a comment, you may wish to print as hexadecimal or even use your literals as hexadecimal.
Using the precision format specifier is the correct answer, but to print all available precision, simply refrain from specifying the number of digits to display:
// prints 1
println!("{:.}", 1_f64);
// prints 0.000000000000000000000000123
println!("{:.}", 0.000000000000000000000000123_f64);
This way, you will not truncate values nor will you have to trim excess zeros, and the display will be correct for all values, regardless of whether they are very large or very small.
Playground example
For completeness, the precision format specifier also supports a specifying a fixed precision (as per the accepted answer):
// prints 1.0000
println!("{:.4}", 1_f64);
as well as a precision specified at runtime (does not need to be const, of course):
// prints 1.00
const PRECISION: usize = 2;
println!("{:.*}", PRECISION, 1_f64); // precision specifier immediately precedes positional argument
This answer was written for Rust 0.12.0 and doesn't apply to Rust 1.x.
You can use the to_string function in std::f32 (not to be confused with the to_string method):
fn main() {
println!("{}", std::f32::to_string(unsafe { std::mem::transmute::<i32, f32>(1) }));
println!("{}", std::f32::to_string(unsafe { std::mem::transmute::<i32, f32>(16) }));
println!("{}", std::f32::to_string(std::f32::MIN_POS_VALUE));
println!("{}", std::f32::to_string(std::f32::MAX_VALUE));
println!("{}", std::f32::to_string(std::f32::consts::PI));
}
Output:
0.00000000000000000000000000000000000000000000140129852294921875
0.000000000000000000000000000000000000000000022420775890350341796875
0.000000000000000000000000000000000000011754944324493408203125
340282368002860660002286082464244022240
3.1415927410125732421875
This answer was written for Rust 0.12.0 and doesn't apply to Rust 1.x.
You can use std::f32::to_string to print all the digits.
use std::f32;
fn main() {
let pi: f32 = 3.1415926536897932384626;
let k1: f32 = 0.6072529350088812561694; // 1/k
println!("pi is {}", f32::to_string(pi));
println!("k1 is {}", f32::to_string(k1));
}
Output:
pi is 3.1415927410125732421875
k1 is 0.607252979278564453125
To trim trailing zeros and dots, you can do:
println!(
"number = {}",
format!("{:.2}", x).trim_end_matches(['.', '0'])
);
Examples:
input
output
3.359
3.36
3.3
3.3
3.0
3
IMHO there is no way around the bigdecimal crate, if you want to store floating-point numbers with high precision:
use bigdecimal::BigDecimal;
fn main() {
let pi = BigDecimal::parse_bytes(b"3.1415926536897932384626", 10);
let k1 = BigDecimal::parse_bytes(b"0.6072529350088812561694", 10); // 1/k
println!("pi is {pi:?}");
println!("k1 is {k1:?}");
}
gets:
pi is Some(BigDecimal("3.1415926536897932384626"))
k1 is Some(BigDecimal("0.6072529350088812561694"))
In Xcode /Objective-C for the iPhone.
I have a float with the value 0.00004876544. How would I get it to display to two decimal places after the first significant number?
For example, 0.00004876544 would read 0.000049.
I didn't run this through a compiler to double-check it, but here's the basic jist of the algorithm (converted from the answer to this question):
-(float) round:(float)num toSignificantFigures:(int)n {
if(num == 0) {
return 0;
}
double d = ceil(log10(num < 0 ? -num: num));
int power = n - (int) d;
double magnitude = pow(10, power);
long shifted = round(num*magnitude);
return shifted/magnitude;
}
The important thing to remember is that Objective-C is a superset of C, so anything that is valid in C is also valid in Objective-C. This method uses C functions defined in math.h.