Jump to content

Rust for the Novice Programmer/Numbers

100% developed
From Wikibooks, open books for an open world

Numbers

[edit | edit source]

Computers are great at handling numbers.
Here, we will see how to do basic mathematical operations in Rust.

First, let's copy the steps from the previous page to ensure we have a clean slate to begin with:

  1. Make a new folder in your projects folder, call it something like "numbers"
  2. Open a terminal inside that new folder and type 'cargo init'
  3. Open src/main.rs in your text editor

Now to print out a number, we have to change the println!("Hello, world!"); line.
To print out a number we will change it to

 println!("{}", 5);

If we type 'cargo run' in the terminal now, we will see 5 in the terminal.

What is this?
Note there aren't "" quotes around 5, that means it is a number.
However, println!() expects some text(normally called a 'string') inside it, so instead we put "{}" where the {} braces are a placeholder for the next input. That next input being the 5 we put after the comma. Thus, the 5 is printed to the terminal. This might seem odd but it is helpful for doing more complex things.

Now, what maths things can we do? The most obvious things to do are the basic operations: addition, subtraction, multiplication and division.

Addition is simple: put a + between two numbers, so

 println!("{}", 5+4);

will print out 9 to the terminal. Subtraction is equally simple with a - between the numbers,

 println!("{}", 5-1);

will print out 4 to the terminal.

Multiplication is the same idea, but uses the * symbol:

 println!("{}", 5*3);

will print out 15 to the terminal.

Division uses the / symbol but functions a little strangely:

 println!("{}", 15/3);

will print out 5 to the terminal.

However,

 println!("{}", 15/6);

doesn't print out 2.5 but instead prints out 2. The reason for this will be explained later, but the mechanic is that the number is rounded down to the nearest whole number.

But this is quite inconvenient to include these calculations in the println!() statements, what's a better way to organise our code?

Next: Variables