I Keep Getting a Funny Result when i cout<<array[100]/customers(50)*100 the result is some weird number, 11478562 when it should be more like 20 or something in that region
I Keep Getting a Funny Result when i cout<<array[100]/customers(50)*100 the result is some weird number, 11478562 when it should be more like 20 or something in that region
Post some code.
Here Is the Code
Code:#include <iostream> using namespace std; int Another(); int main() { int code; int code_arr[100]; int counter_arr[100]; int customers=0; int i; for(i=0; i<100; ++i) { code_arr[i]=0; counter_arr[i]=0; } while(Another()) { cout<<"Enter Your Zip Code:"; cin>>code; cout<<endl; for(i=0; i<100; ++i) { if(code_arr[i]==code) { counter_arr[i]+=1; cout<<"Added Counter!!"<<endl; ++customers; break; } } if(i>=100) for(i=100; i>0; --i) { if(code_arr[i]==0) { code_arr[i]=code; counter_arr[i]+=1; cout<<"Added Address!!"<<endl; ++customers; break; } } } for(int l=0; l<100; ++l) if(code_arr[l]>0) { cout<<"Zip Code #"<<l+1<<endl <<"Zip Code #"<<code_arr[l]<<endl <<"Number Of Zip Codes from this area : # "<<counter_arr[l]<<endl <<"Total % of total customers : "<<t<<endl<<endl; } cout<<"Total Customers All Up : "<<customers<<endl<<endl; return 0; } int Another() { int response; cout<<endl; cout<<"Would You Like to Process Another Zip Code : "; cin>>response; cout<<endl; return response; }
the last part is the worry, and i forgot to add it!!
here is the problem
Code:<<"Total % of total customers : "<<counter_arr[l]/customers*100<<endl<<endl;
Given that all these variables are int, I would expect you to get 0 as an answer. (Assuming counter_arr[l] < customers, that division will give 0, and 0*100 is 0.)
i see, beginners ignorance, and lack of sleep, thanks for that....
i see i got to use doubles i forgot that principal, maths in c++ is a different thing, you got to be aware of doubles and int etc as well
This causes out-of-bounds access.Code:for(i=100; i>0; --i) { if(code_arr[i]==0)
Because of integer division this should always print 0: smaller / larger = 0 if smaller and larger are integers.Code:<<"Total % of total customers : "<<counter_arr[l]/customers*100<<endl<<endl;
You can try multiplying by 100 first, or cast customers or counter_arr[l] or both to double to force floating point division.
An easier way to write this kind of program is to use std::map (something like):
Code:map<int, int> zip; do { cout<<"Enter Your Zip Code:"; cin>>code; cout<<endl; ++zip[ code]; //this does the logic of your two for-loops } while (Another()); //print statistics
Last edited by anon; 06-12-2008 at 08:25 AM.
I might be wrong.
Quoted more than 1000 times (I hope).Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.