CodeBlanks Logo Icon CodeBlanks

Project skeleton

Set up the calculator project skeleton with main and println!.

Project: a calculator

In this project you will write a command-line calculator that reads an expression like 12 * 3 from the user and prints the result. First set up the structure: reading input, parsing, computing and handling errors will live in separate functions.

fn hesapla(a: f64, op: char, b: f64) -> Result<f64, String> {
    // + - * / operations
}

fn main() {
    // loop: read → parse → compute → print
}

Why f64?

Because 7 / 2 is expected to give 3.5, numbers are kept as f64. When printing, {} hides needless zeros: 3.5 → 3.5, 36.0 → 36. Throughout the project you'll move in small steps and try each piece inside main.

Practice First operation

Write the fn topla(a: f64, b: f64) -> f64 function and try it with println!("{}", topla(2.0, 1.5));.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn topla(a: f64, b: f64) -> f64 {
    a + b
}

fn main() {
    println!("{}", topla(2.0, 1.5));
}

Expected output

3.5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why does <code>hesapla</code> return <code>Result&lt;f64, String&gt;</code>?

  • Because it's required
  • To be able to report errors such as division by zero and unknown operators Correct answer
  • Because it's faster
  • Because f64 can't be printed

Explanation: Result carries either the successful value (Ok) or the error (Err); the caller is forced to handle both.

2 Decimal parameter

Question
fn topla(a: ____, b: f64) -> f64 {
    a + b
}
Answer
fn topla(a: f64, b: f64) -> f64 {
    a + b
}

Explanation: f64 is Rust's default 64-bit floating-point type.

3 Part and role

Term Meaning
main Loop and flow
hesapla Performs the operation
Result Success or error
f64 Decimal result

All lessons in Beginner