Fondamenti di Rust
Rust Operators and Arithmetic
Why is 17 / 5 equal to 3 in Rust? Learn arithmetic, comparison and logical operators.
Cosa imparerai
- + - * / and %
- Integer division
- Comparisons with && and ||
Expression → result
17 / 5317 % 5217 as f64 / 5 as f643.42_i32.pow(10)1024How Rust evaluates an expression
Operators combine values into expressions. Rust follows the usual math rules, with one thing to remember: dividing two integers drops the fraction.
17 / 5 is 3 because both numbers are integers, and 17 % 5 is the remainder 2. Converting both sides with as f64 keeps the fraction. && is true only when both comparisons are true, and pow raises a number to a power.
Punti chiave
- int / int drops the fraction: 17 / 5 is 3.
- % gives the remainder: 17
%5 is 2. - Convert with as f64 to keep the fraction.
Esempio Rust eseguibile
main.rs
fn main() {
let a = 17;
let b = 5;
println!("{} {} {}", a + b, a - b, a * b);
println!("{} {}", a / b, a % b);
println!("{}", a as f64 / b as f64);
println!("{}", a > b && b != 0);
println!("{}", 2_i32.pow(10));
}
22 12 85
3 2
3.4
true
1024Esercitati
Apri l'esempio nel compilatore online, cambia un valore o aggiungi una riga e prova a prevedere l'output prima di eseguirlo. Poi rompi il codice di proposito e leggi il messaggio del compilatore.
Hai finito questa lezione?
Segnala come imparata per tenere traccia dei tuoi progressi.
I tuoi progressi sono salvati in questo browser Accedi per conservarli su ogni dispositivo.
Esercitati con una sfida
Usa ciò che questa lezione spiega per risolvere un problema reale. Ogni sfida gira nel browser, con test immediati e una revisione dell'IA.
- Rectangle Perimeter Compute the perimeter of a rectangle from its sides. Facile
- Interesse Semplice Calcola l'importo totale dopo l'interesse semplice. Facile