You are viewing our Forum Archives. To view or take place in current topics click here.
C++ help +rep for help
Posted:

C++ help +rep for helpPosted:

Acrocide
  • Wise One
Status: Offline
Joined: Jan 06, 201212Year Member
Posts: 503
Reputation Power: 20
Status: Offline
Joined: Jan 06, 201212Year Member
Posts: 503
Reputation Power: 20
I've got a quick question. I'm trying to do lab 6A and the only thing i'm stuck on is trying to count the frequency of 42 appearing in srandom. here is what I have:

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
int count = 1000;
int range = 100;
int value = 42;
int found = 0;

int seed;
cout << "Enter seed: ";
cin >> seed;
srand(seed);


for (int i=0; i < count; i++)
{
int num = random() % range;
cout << num << " ";
}
if (found==value)
found= found++;


cout << "\nthe value " << value
<< " was found " << found << " times\n";
return 0;
}

what am I doing wrong? I'm getting so frustrated and the only thing I can find online is search arrays, which we haven't done in class. thanks
#2. Posted:
Acrocide
  • Wise One
Status: Offline
Joined: Jan 06, 201212Year Member
Posts: 503
Reputation Power: 20
Status: Offline
Joined: Jan 06, 201212Year Member
Posts: 503
Reputation Power: 20
Can anyone help? It would be appreciated.
#3. Posted:
noizzy
  • New Member
Status: Offline
Joined: Jan 21, 201410Year Member
Posts: 8
Reputation Power: 0
Status: Offline
Joined: Jan 21, 201410Year Member
Posts: 8
Reputation Power: 0
If i understand what you want to do right, your error is here:
for (int i=0; i < count; i++)
{
int num = random() % range;
cout << num << " ";
}
if (found==value)
found= found++;

Im thinking it should be:
for (int i=0; i < count; i++)
{
int num = random() % range;
cout << num << " ";
if (num==value) ++found;
}

you're checking to see if 'num'==42 OUTSIDE of the for loop wich is only giving you ONE evaluation and of the wrong thing because found is declared as 0 and stays that way in your current state. You want to check EVERY iteration of the for loop to see if 'num' is equal to 42 and if it is THEN you increment 'found'

Edit: you may also want to look into putting a range on random(), I havent used it in a while, but I recall being able to do something like random(min, max), so in your case random(0, range). But i cant remember if C++ has that syntax or not
Jump to:
You are viewing our Forum Archives. To view or take place in current topics click here.