Tuesday, July 14, 2009

C++ Help Please!?

Ok guys. What I have to do is write an array that reads 10 numbers and displays how many are divisible by three. I wrote the code, but what I don't understand is that is always outputs 1 less then what the answer should be. What do I need to do to fix it? This is code I have made so far:





#include %26lt;iostream%26gt;


using namespace std;





int main()


{


const int TOTALNUMBERS = 10;


int numbers[TOTALNUMBERS];





// Read all numbers


for (int i = 0; i %26lt; TOTALNUMBERS; i++)


{


cout %26lt;%26lt; "Enter a number: ";


cin %26gt;%26gt; numbers[i];


}


// Find numbers divisible by 3


int div = numbers[0];


for (int i = 0; i %26lt; TOTALNUMBERS; i++)





if (div / 3)


div = numbers[i];








cout %26lt;%26lt; "Numbers divisible by three: " %26lt;%26lt; div %26lt;%26lt;endl;





return 0;





}








Thanks!

C++ Help Please!?
Got a little logic error going on... You're OK up to the find numbers portion.








// Find numbers divisible by 3


int div =0; /* CHANGED; just to keep track of them */





/* Added brackets */


for (int i = 0; i %26lt; TOTALNUMBERS; i++) {


/*Use the MOD operator. This will yield the remainder of the division */


if ((numbers[i]% 3)==0)


div ++;


}


cout %26lt;%26lt; "Numbers divisible by three: " %26lt;%26lt; div %26lt;%26lt;endl;





return 0;





}








P.S. Your FOR condition is fine!

survey monkey

No comments:

Post a Comment