On Thursday 20 August 2015 22:31, Unknow wrote: > I'm writed a program for calculating the e number. I can compile > the source code but when i try run the program, system gives > 'program stopped working' error. > > Source code; > """ > // main.d > > module main; > > import std.file; > import std.conv; > > long factorial(long i){ > if (i == 0){ > return 1; > }else{ > return(i * factorial(i-1)); > } > } > > void main(string[] args){ > real *e; e = new real; *e = 0; long *integer; integer = new > long; *integer = 1; > for(; *integer <= 100; *integer++){ > *e = (*e) + (*integer / factorial(*integer)); > } > if(exists("e") != 0) > { > std.file.write("e", to!string(*e)); > }else{ > //... > } > delete(e); delete(integer); > } > """
This has a couple issues. 1) The factorial gets huge quickly. For example, factorial(100) definitely won't fit in a long. It'll wrap around and give wrong results. 2) *integer++ doesn't do what you think it does. The increment is done before the dereference. You could fix this, but: 3) Don't use pointers like that. You really don't need to new reals and longs like that. 4) `*integer / factorial(*integer)` does integer division, which you don't want there. You can multiply with `1.0` (a floating point number) to force floating point division: `*integer * 1.0 / factorial(*integer)`. 5) I'm not sure what you want the `exists` condition to do. The way it is, the file "e" is only (over)written when it exists already. This may not be what you want. Better write it like this: ---- if(exists("e")) { /* Do what you want when the file exists. */ } else { /* Do what you want when the file doesn't exist. */ } ---- 6) Don't use delete unless you know exactly what you're doing (which you don't yet). Here's a cleaned up version of your code: ---- module main; import std.stdio: writeln; long factorial(long i){ if (i == 0){ return 1; }else{ return(i * factorial(i-1)); } } void main(string[] args){ real e = 0; long integer = 1; for(; integer <= 10; integer++){ e = e + integer * 1.0 / factorial(integer); } writeln(e); /* 2.71828 */ } ---- I severely limited the range of integer. I don't know off the top of my head how large you can make it without hitting overflow. I removed the file writing, because I'm not sure if you want to write it only when it doesn't exist, or only overwrite when it does exist.