// end is the end of current expression int calc_iter(char *code, char **end) { char numbuf[100]; if (code[0] != '(') { // we are reading a number int i = 0; for (; code[i] && isdigit(code[i]); i++) { numbuf[i] = code[i]; } numbuf[i] = 0; *end = code + i; return atoi(numbuf); } int v1, v2; char *end1, *end2; // skip '(+ ', so code + 3 v1 = calc_iter(code+3, &end1); // skip the space between 2 expressions v2 = calc_iter(end1+1, &end2); // skip ')' *end = end2 + 1; // see the operator switch(code[1]) { case '+': return v1 + v2; case '-': return v1 - v2; case '*': return v1 * v2; case '/': return v1 / v2; } }
int main() { const auto xScale = (maxX - minX) / resX; const auto yScale = (maxY - minY) / resY; std::ofstream out("Mandelbrot.ppm"); assert(out); out << "P3\n"; out << resX << " " << resY << "\n"; out << maxColor << "\n"; for(auto i = 0; i < resX; i++) { for(auto j = 0; j < resY; j++) { auto real = minX + xScale * i; auto imag = maxY - yScale * j; std::complex<float> c(real,imag); Color color = calc_iter(c); out << color.red << " " << color.green << " " << color.blue << " "; } out << "\n"; } out.close(); return 0; }
int calc(char *code) { char *end; return calc_iter(code, &end); }