Skip to content

Instantly share code, notes, and snippets.

@mcb2003
Created April 25, 2021 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcb2003/6f6779fce0af8bd9881b63636a280f3f to your computer and use it in GitHub Desktop.
Save mcb2003/6f6779fce0af8bd9881b63636a280f3f to your computer and use it in GitHub Desktop.
Got sick of not having a calculator that can solve quadratics, so I made one. In Rust!
use std::{error::Error, io::{self, prelude::*}};
fn main() -> Result<(), Box<dyn Error>> {
let variable = std::env::args().nth(1).unwrap_or("x".into());
let a = read_f64("A: ")?;
let b = read_f64("B: ")?;
let c = read_f64("C: ")?;
let descriminent = descrim(a, b, c);
let pos = pos_solution(a, b, descriminent);
let neg = neg_solution(a, b, descriminent);
let desc_string = format!("\\sqrt{{{}^2-4\\times {}\\times {}}}", b, a, c);
println!("\n${}x^2{:+}x{:+} = 0$:", a, b, c);
println!("Descriminent:\t${} = {}$", desc_string, descriminent);
println!("Pos Solution:\t$\\frac{{{}+{}}}{{2\\times {}}} = {}$", b, desc_string, a, pos);
println!("Neg Solution:\t$\\frac{{{}-{}}}{{2\\times {}}} = {}$", b, desc_string, a, neg);
println!("$({0}{1:+})({0}{2:+}) = 0$", variable, neg, pos);
println!("${0} = {1}$ or ${0} = {2}$", variable, -pos, -neg);
Ok(())
}
fn read_f64(prompt: &str) -> io::Result<f64> {
let mut buf = String::new();
loop {
buf.clear();
print!("{}", prompt);
io::stdout().flush()?;
io::stdin().read_line(&mut buf)?;
match buf.trim().parse() {
Ok(val) => return Ok(val),
Err(e) => {
eprintln!("{}", e);
continue
},
}
}
}
fn descrim(a: f64, b: f64, c: f64) -> f64 {
((b*b) - (4.0*a*c)).sqrt()
}
fn pos_solution(a: f64, b: f64, desc: f64) -> f64 {
(b+desc) / (2.0*a)
}
fn neg_solution(a: f64, b: f64, desc: f64) -> f64 {
(b-desc) / (2.0*a)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment