if calculate 0,703125 / 2
calc.exe, 0,3515625
. however, if same in c++ 0,351563
. how can turn rounding off? need full number.
background
i try find out if true pattern in following example result 9.
360° = 3+6+0 = 9 180° = 1+8+0 = 9 90° = 9+0 = 9 45° = 4+5 = 9 22.5° = 2+2+5 = 9 11.25° = 1+1+2+5 = 9 5.625° = 5+6+2+5 = 18 = 1+8 = 9 2.8125° = 2+8+1+2+5 = 18 = 1+8 = 9 1.40625 = 1+4+0+6+2+5 = 18 = 1+8 = 9 0.703125 = 0+7+0+3+1+2+5 = 18 = 1+8 = 9 0.3515625 = 0+3+5+1+5+6+2+5 = 27 = 2+7 = 9 0.17578125 = 0+1+7+5+7+8+1+2+5 = 36 = 3+6 = 9 ...
i wrote the code this, because c++ rounds values, false results. how can solve this?
code
#include<iostream> #include<sstream> #include<string> #include<math.h> /* pow */ using namespace std; int checksum(int param) { int sum = 0; while (param > 0) { int r1 = param % 10; sum += r1; param /= 10; } while (sum > 9) { sum = checksum(sum); } return sum; } //this function takes double , separates in 2 parts. //the part in front of point, , part behind point. //then calls checksum function both of them , gives result. int tesla(double param) { int front_part = static_cast<int>(param); double after_point_part = param - front_part; ostringstream strs; strs << after_point_part; string after_point_part_str = strs.str(); int nachkomma_len = after_point_part_str.length()-1; after_point_part *= pow(10.00,nachkomma_len-1); strs.str(""); //so leert man einen stringstream strs << after_point_part; after_point_part_str = strs.str(); int after_point_part_int = stoi(after_point_part_str); int sum = 0; sum = checksum(front_part); sum += checksum(after_point_part_int); sum = checksum(sum); return sum; } int main() { double number; cout<<"enter number:"<<endl; cin>> number; int zähler = 100; for(int i=0; < zähler; i++) { int erg = tesla(number); cout<<"the checksum of "<<number<<" "<< erg <<endl; number /= 2; } cin.get(); cin.get(); return 0; }
there number of things going on here:
the number see printed enjoyment (or perhaps, frustration). if want see better precision default, specify want see better precision default. how number printed , how represented 2 different things.
you need use double precision if want more 6 or decimal places of precision. need use kind of extended precision if want more fifteen or decimal places of precision.
ultimately, there no escape. representing rational numbers require computer infinite memory. can't represent rationals in full detail on finite binary (or digital) computer.
to represent real numbers beyond that. number of real numbers uncountable.
Comments
Post a Comment