I'm creating a small program that allows the user to input 3 names (or whatever string they want). The program should then display all three strings (which is working), then it should use the rand() function to randomly display one of the three strings. This is the part that isn't functioning properly.
#include <iostream>
#include <string>
using namespace std;
void display(string[], int);
const int SIZE = 3;
int main()
{
string names[SIZE];
for (int i = 0; i < SIZE; i++)
{
cout << i + 1 << ": ";
getline(cin, names[i]);
}
cout << endl;
display(names, SIZE);
int name = rand() % (2 + 1 - 0) + 0;
cout << names[name];
cin.get();
return 0;
}
void display(string nm[], int n)
{
int i = 0;
for (i; i < n; i++)
{
cout << "Name " << i + 1 << ": ";
cout << nm[i] << endl;
}
}
I had it set up differently before, and it gave me an error, but after changing it to what it is now, it always gives me the last element [2].
Is this a code error, or is it just that rand() always gives the same output on the same system?
After some discussion in the comments, it became apparent that the issue was that I was not seeding the rand() function. Below is part of the code that was not functioning, corrected.
(Also, as a sidenote, to use the time() function, <ctime> or <time.h> has to be included.)
srand(time(NULL));
int name = rand() % 3;
cout << names[name];
(Thanks to #manni66 for pointing out that it was useless to include an overly complicated calculation to get the range for rand(), as it just had to be a single integer.
seeding with current time works :
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <cstdio>
using namespace std;
void display(string[], int);
const int SIZE = 3;
int main()
{
string names[SIZE];
for (int i = 0; i < SIZE; i++)
{
cout << i + 1 << ": ";
getline(cin, names[i]);
}
cout << endl;
display(names, SIZE);
srand(time(NULL)); // use current time as seed for random generator
int name = rand() % 3 ;
printf(" random %i \n", name);
cout << names[name];
cin.get();
return 0;
}
void display(string nm[], int n)
{
int i = 0;
for (i; i < n; i++)
{
cout << "Name " << i + 1 << ": ";
cout << nm[i] << endl;
}
}
Related
What I'm trying to output is the dealer's roll (the numbers are supposed to be stored in an array) but I keep getting an error that int is an invalid type in DealerRoll(dealerRoll[3]);
#include <iostream>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
//Dice Rolls
int DealerRoll(int dealerRoll[3]) {
srand (time(NULL));
for (int dealerCount = 0; dealerCount < 3; dealerCount++) {
dealerRoll[dealerCount] = rand()% 6+1;
cout << dealerRoll[dealerCount] << " ";
}
return dealerRoll[3];
}
int main() {
int dealerRoll;
cout << "Dealer's Roll: " << endl;
DealerRoll(dealerRoll[3]);
system ("pause");
return 0;
}
Although you can make an array in a function, std::vector provides better flexibility, and deals with resource management for you.
If array size is fixed, you can use std::array<int,3> instead:
void DealerRoll(std::array<int,3>& dealerRoll) {
srand (time(NULL));
for (int dealerCount = 0; dealerCount < 3; dealerCount++) {
dealerRoll[dealerCount] = rand()% 6+1;
cout << dealerRoll[dealerCount] << " ";
}
}
...
int main() {
std::array<int,3> dealerRoll;
cout << "Dealer's Roll: " << endl;
DealerRoll(dealerRoll);
...
}
Change the line int dealerRoll; as int dealerRoll[3];
Reason: You need to pass the array to function but you are declaring the integer variable.
Change the line DealerRoll(dealerRoll[3]); as DealerRoll(dealerRoll);
Reason: Function takes array as input but you have passed the 3rd position of array(Which will decompose to integer) instead of array.
#include <iostream>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
//Dice Rolls
void DealerRoll(int* dealerRoll) //retrieving array in pointer
{
srand (time(NULL));
for (int dealerCount = 0; dealerCount < 3; dealerCount++)
{
dealerRoll[dealerCount] = rand()% 6+1;
cout << dealerRoll[dealerCount] << " ";
}
}
int main()
{
int dealerRoll[3]; //syntax for creating array
cout << "Dealer's Roll: " << endl;
DealerRoll(dealerRoll); //passing address of array in function
//As Values are passed by address, values retained in array
cout<<"\nValues in Dealer's Roll : "<<endl;
for (int dealerCount = 0; dealerCount < 3; dealerCount++)
{
cout << dealerRoll[dealerCount] << " ";
}
system ("pause");
return 0;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Hi i'm trying to Write a program in C++ to, generate and print 20 random numbers, between 0 to 999, and do the following operations without using inbuilt functions, find and print the: min value, max value, average, median, standard deviation, variance. Do a binary search on the 15th element. Please help me with the code.
So far i've done this much
#include
#include
#include
using namespace std;
void minimum(int[], int);
void maximum (int[], int);
void average(int[], int);
void median(int[], int);
void mean(int[], int);
void sort(int[], int);
int ra()
{
int r = rand() % 1000;
return r;
}
int main ()
{
srand(time(NULL));
ra();
int array[20];
int num=20;
for (unsigned int i = 0; i < num; i++)
{
array[i] = ra();
cout << "Index: " << i << ", random number: " << array[i] << endl;
}
minimum();
new_array[20];
num=20;
for (unsigned int i = 0; i < num; i++)
{
new_array[i] = new_array();
cout << "Index: " << i << ", random number: " << minimum << endl;
}
return 0;
}
void minimum(int new_array[], int num)
{
for (unsigned int i = 0; i < num; i++)
if (new_array[i] minimum)
minimum = new_array[i];
cout << "Maximum value: " << minimum << endl;
}
void maximum (int new_array[], int num)
{
for (unsigned int i = 0; i < num; i++)
if (new_array[i] > maximum)
maximum = new_array[i];
cout << "Maximum value: " << maximum << endl;
return 0;
}
void median(int new_array[], int num)
{
//CALCULATE THE MEDIAN (middle number)
if(num % 2 != 0){// is the # of elements odd?
int temp = ((num+1)/2)-1;
cout << "The median is " << new_array[temp] << endl;
}
else{// then it's even! :)
cout << "The median is "<< new_array[(num/2)-1]<<new_array[num/2]< endl;
}
mean(new_array, num);
}
void sort(int new_array[], int num)
{
//ARRANGE VALUES
for(int x=0; x<num; x++){
for(int y=0; y<num-1; y++){
if(new_array[y]>new_array[y+1]){
int temp = new_array[y+1];
new_array[y+1] = new_array[y];
new_array[y] = temp;
}
}
}
cout << "List: ";
for(int i =0; i<num; i++){
cout << new_array[i] << " ";
}
cout << "\n";
median(new_array, num);
}
void average_(int new_array[], int nums)
{
float sum;
for (unsigned int i = 0; i < 20; ++i)
{
sum+=num;
}
cout << "Average value: " << average_/num << endl;
}
Please tell the necessary corrections
You have a ways to go, your code does not do any of the things you want yet. However, you mentioned that you are a beginner so I fixed your code and set up a basic structure of how to get going. I left comments on what I changed and what you need to do. That being said, I don't know what you mean by "Do a binary search on the 15th element"
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int ra()
{
// You wanted a number between 0 and 999 inclusive so do not add 1
// Instead do a modulus of 1000
int r = rand() % 1000;
return r;
}
int main ()
{
// Do this to get different random numbers each time you run your program
srand(time(NULL));
// You have to call ra as a function. Do this by writing: ra()
// Here I am storing 20 random numbers in an array
int nums[20];
for (unsigned int i = 0; i < 20; ++i)
{
nums[i] = ra();
cout << "Index: " << i << ", random number: " << nums[i] << endl;
}
// Iterate to find the minimum number
int minimum = nums[0];
for (unsigned int i = 1; i < 20; ++i)
if (nums[i] < minimum)
minimum = nums[i];
cout << "Minimum value: " << minimum << endl;
// TODO: Find the maximum in basically the same way
// TODO: Find the average by summing all numbers then dividing by 20
// TODO: Find the median by sorting nums and taking the average of the two center elements
// TODO: etc.
return 0;
}
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int r;
int ra;
int i=0;
int ra(){
r = (rand() % 999) + 1;
return r;
}
int main ()
{
int random_;
srand((int)time(0));
while (i++ < 20)
{
random_ = r;
cout<< random_<<endl;
}
return 0;
}
I need to pass an user input integer to a sumTotal(& userInt) function.
If the int is 2341 I need to sum 2+3+4+1 = 10 and return the value to main!
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// The program needs to input an integer like 2341, then sum it as 2+3+4+1 + 10
// I am in putting an integer and will pass it to a funtion by &.
int main()
{
string strNumber;
int intNumber = 0;
cout << "Enter your number: ";
cin >> intNumber;
// programming the logic for sumTotal(& intNumber) function before creating
strNumber = to_string(intNumber);
cout << "Your number is: " << strNumber << endl;
cout << "Your numbers length: " << strNumber.length() << " digits" << endl;
// here I need to convert the string array to an integer array
for (int i = 0; i < strNumber.length(); ++i){
intNumber[&i] = strNumber[i] - '0';
cout << "Element [" << i << "] contains: " << strNumber[i] << endl;
}
// next a recursive function must sum the integer array
// I am taking an online course and cant afford a tutor please help!
system("pause");
return 0;
}
if you want recursion ,you don't need any string work,try this :
#include <iostream>
using namespace std;
int recSum(int);
int main(){
int i;
cin>>i;
cout<<recSum(i);
return 0;
}
int recSum(int i){
return i==0?0:i%10+recSum(i/10);
}
recursion on array version
#include <iostream>
using namespace std;
int recSum(int* ary,int len){
return len<0?0:ary[len]+recSum(ary,len-1);
}
int main(){
int j[]={1,2,3,4,5,6,7,8,9,10};
cout<<recSum(j,9);
}
A simple and efficient method is to keep the number as a string and access the digits one at a time.
Note the equation:
digit_number = digit_character - '0';
Also, knowing that when summing digits, the order is irrelevant. So, we have:
sum = 0;
for (i = 0; i < string.length(); ++i)
{
sum += string[i] - '0';
}
A string is an array of chars. To convert a char to an int you have to do 'char' - '0'.
I wrote a couple of versions.
Pick whichever one you like best.
#include <iostream>
#include <string>
int main()
{
std::string str = "1234";
int sum = 0;
//pre C++11
for (std::string::iterator i = str.begin(); i != str.end(); ++i)
sum += (*i - '0');
//C++11
sum = 0;
for (auto i = str.begin(); i != str.end(); ++i)
sum += (*i - '0');
//ranged-for
sum = 0;
for (const auto &i : str)
sum += (i - '0');
std::cout << "Sum: " << sum;
std::cin.get();
}
For some odd reason, I have an assignment to shuffle the contents of a vector without using the shuffle or random_shuffle functions that are available in the C++ standard library. The following is some basic code with a (non-functioning) function to do the job to give you a clearer idea of what I'm getting at:
#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
// Shuffle Vector Function:
void shuffle_vector(std::vector<string> &names)
{
}
// end function
int main(void)
{
srand(time(0));
vector<string> names;
names.push_back("Sally");
names.push_back("Sue");
names.push_back("Bob");
names.push_back("Fred");
cout << "Your names:" << endl;
for (int i = 0; i < names.size(); i++)
{
cout << i + 1 << ". " << names[i] << endl;
}
cout << "Press Enter to shuffle.";
cin.get();
shuffle_vector(names);
cout << "\nYour shuffled names:" << endl;
for (int i = 0; i < names.size(); i++)
{
cout << i + 1 << ". " << names[i] << endl;
}
cin.get();
}
The way I thought to do it is to:
"push_back" the vector to create a temporary spot
randomly assign an index into the temporary spot
randomly assign an index into the newly-empty spot
put the index in the temporary spot into the last remaining empty index
"pop_back" the vector to its original size
(like with switching indexes in arrays)
I don't know how exactly to execute this but also--more importantly--if this would even work or if it's the best way to go about it. How would you do it?
Bam! This was actually pretty fun to figure out!
I used rand and a "for" loop that iterated 100 times to randomize it. I also added a "temporary" index that was deleted after the shuffling was complete.
#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
// Shuffle Vector Function:
void shuffle_vector(std::vector<string> &names)
{
for (int i = 0; i < 100; i++)
{
int randomIndex = rand() % names.size();
int randomIndex2 = rand() % names.size();
if (randomIndex2 == randomIndex) // make sure the two random values aren't the same
{
do {
randomIndex2 = rand() % names.size();
} while (randomIndex2 == randomIndex);
}
names.push_back("temporary"); // create temporary index at the end of the vector
int last_index_number = (names.size() - 1);
names[last_index_number] = names[randomIndex];
names[randomIndex] = names[randomIndex2];
names[randomIndex2] = names[last_index_number];
names.pop_back(); // bring vector back to original size
}
}
// end function
int main(void)
{
srand(time(0));
vector<string> names;
names.push_back("Sally");
names.push_back("Sue");
names.push_back("Bob");
names.push_back("Fred");
cout << "Your names:" << endl;
for (int i = 0; i < names.size(); i++)
{
cout << i + 1 << ". " << names[i] << endl;
}
cout << "Press Enter to shuffle.";
cin.get();
shuffle_vector(names);
cout << "\nYour shuffled names:" << endl;
for (int i = 0; i < names.size(); i++)
{
cout << i + 1 << ". " << names[i] << endl;
}
cin.get();
}
For some reason "0" is being outputted even though I didn't assign it to the set of numbers in the array. How can I get rid of the zero?
#include <iostream>
#include <time.h>
#include <string>
using namespace std;
int n;
int size=10;
int setNums[10];
int main()
{
string ans = "";
do {
for (int n=0; n<size;n++ )
{
setNums[size] = n+1;\
cout << setNums[size] << endl;
}
srand (time(NULL));
int choice = rand() % setNums[size];
cout << choice << endl;
cout << "Keep guessing?" << endl;
cin >> ans;
} while (ans == "Y");
cout << "\n\n...Press ENTER to Exit System...";
cin.get();
return 0;
What you want is to find the index, not the value itself. Change this:
int choice = rand() % setNums[size];
to this:
int choice = setNums[rand() % size];
Also, the assignment is always being performed upon the index size. You should have:
...
for (int n=0; n<size;n++ ) {
setNums[n] = n+1;\
cout << setNums[n] << endl;
}
You're misusing setNums, and you don't need it at all. Just do this:
int choice = rand() % size + 1;