这是《Rust实战》中的2.7项目,我创建了一个项目,然后也下载了num放入了cargo.toml。 代码检查了一下也没有问题,但对应书上的代码会报错,可能是所有权的问题,请大佬们帮忙看看。
Code
use num::complex::Complex;
fn calculate_mandelbrot(
max_iters: usize,
x_min: f64,
x_max: f64,
y_min: f64,
y_max: f64,
width: usize,
height: usize,
) -> Vec<Vec<usize>> {
let mut rows: Vec<_> = Vec::with_capacity(width);
for img_y in 0..height {
let mut row: Vec<usize> = Vec::with_capacity(height);
for img_x in 0..width {
let x_percent = img_x as f64 / width as f64;
let y_percent = img_y as f64 / height as f64;
let cx = x_min + (x_max - x_min) * x_percent;
let cy = y_min + (y_max - y_min) * y_percent;
let escaped_at = mandelbrot_at_point(cx, cy, max_iters);
row.push(escaped_at);
}
all_rows.push(row);
}
rows
}
fn mandelbrot_at_point(
cx: f64,
cy: f64,
max_iters: usize,
) -> usize {
let mut z = Complex { re: 0.0, im: 0.0 };
let c = Complex::new(cx, cy);
for i in 0..=max_iters {
if z.norm() > 2.0 {
return i;
}
z = z * z + c;
}
max_iters
}
fn render_mandelbrot(escape_vals: Vec<Vec<usize>>) {
for row in escape_vals {
let mut line = String::with_capacity(row.len());
for column in row {
let val = match column {
0..=2 => ' ',
2..=5 => '.',
5..=10 => '·',
11..=30 => '*',
30..=100 => '+',
100..=200 => 'X',
200..=400 => '$',
400..=700 => '#',
_ => '%',
};
line.push(val);
}
println!("{line}");
}
}
fn main() {
let mandelbrot = calculate_mandelbrot(1000, 2.0, 1.0, -1.0, 1.0, 100, 24);
render_mandelbrot(mandelbrot);
}
Cargo build
Compiling mandelbrot v0.1.0 (E:\Cx_Blog\11.rust\mandelbrot)
error[E0425]: cannot find value `all_rows` in this scope
--> src\main.rs:25:13
|
25 | all_rows.push(row);
| ^^^^^^^^ not found in this scope
For more information about this error, try `rustc --explain E0425`.
error: could not compile `mandelbrot` due to previous error
1
共 6 条评论, 1 页
评论区
写评论ok了,感谢!
--
👇
soft5: let mandelbrot = calculate_mandelbrot(1000, 2.0, 1.0, -1.0, 1.0, 100, 24); 漏了 let mandelbrot = calculate_mandelbrot(1000, -2.0, 1.0, -1.0, 1.0, 100, 24);
漏了 let mandelbrot = calculate_mandelbrot(1000, -2.0, 1.0, -1.0, 1.0, 100, 24);
显然all_rows错了,另外,你需要知道程序是做什么的,明显现在fn calculate_mandelbrot的调用入参x_min比x_max还大,你可以分别改成-1,1进去调试,这根据你最后希望的效果
--
👇
enomothem: 我也不太清除,书上就是这样写的,把all_删除虽然不会报错了,但运行没有效果
--
👇
Grobycn: 确定不是写错了变量名字?
all_rows
应该指的是rows
这个变量吧。这不是写着未找到么
我也不太清除,书上就是这样写的,把all_删除虽然不会报错了,但运行没有效果
--
👇
Grobycn: 确定不是写错了变量名字?
all_rows
应该指的是rows
这个变量吧。确定不是写错了变量名字?
all_rows
应该指的是rows
这个变量吧。