random number generator related question - c++

So here's the code:
if(rand_s(&number) != 0) cout << "Random number generator failed!" << endl;
Question is - does it mean that the program outputs a failure message every time the random number generated with this rand_s(&number) expression is greater than zero? And if so, why would i want such a thing?
// complete code
unsigned int number = 0;
cout << "Random values are:" << endl;
double max = 1000000.0;
for(int i = 0 ; i<100 ; i++)
{
if(rand_s(&number) != 0)
cout << "Random number generator failed!" << endl;
number = static_cast<unsigned int>(static_cast<double>(number)/UINT_MAX*max)+1;
// output
cout << setw(12) << number;
if((i+1) % 5 == 0) cout << endl;
}

No rand_s returns an errno_t so 0 means there was no error. Anything else is indicating that there was an error when running the function.
More information can be found here

No. here is the link.
rand_s return value: Zero if successful, otherwise, an error code.
Your random value will be: number

The return value of function is 0 if the function execution completes successfully. The result is stored in number. Note that you are passing by address.

Related

Validating input with do while loop

I am trying to minimize hardcoding numbers into my program and allowing for users to define max and min parameters along with making sure that the input is valid.
#include <iostream>
int main(){
int max, A=0;
do
{
std::cout << "What is the max?\n";
std::cin >> max;
if (std::cin.fail()) {
std::cin.clear();
std::cin.ignore();
std::cout << "not an integer, try again\n";
continue;
}
if(max < -1000){
std::cout << "That doesnt make much sense, please enter the max again.\n";
}
} while (max <A); \\HERE IS WHERE THE PROBLEM IS.
std::cout << "The max number of steps are " << max <<std::endl;
return 0;
}
If A is 0 or less, the program doesn't ask for user input again. instead the program just exits the loop.
If A is 1 or more, then then the program loops until a valid input is provided.
I would like the max number to be any int number, including negatives. This is working for positive numbers, but not for maximums that are 0 or less.
do
{
//ask for input
//input taken
} while (A>=1);
This will the code you have to use for the scenario described at the last line. One more point you just forget to assign any value to A according to your logic.
Thanks!
If A is 1 or more, then then the program loops until a valid input is provided. - You are saying exactly what the while loop needs to do. Just implement it.
} while (A >= 1); \\If A is greater than or equal to 1 then loop until valid.
std::cout << "The max number of steps are " << max <<std::endl;
return 0;
}
To answer your follow up question:
} while (A >= 1 && max <= 0); \\If A is greater than or equal to 1 then loop until valid.
std::cout << "The max number of steps are " << max <<std::endl;
return 0;
}
I would suggest writing a custom function that takes an acceptable range of min/max values as input parameters, eg:
int promptForInt(const string &prompt, int minAllowed, int maxAllowed)
{
int value;
std::cout << prompt << "\n";
do
{
if (!(std::cin >> value)) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "not an integer, try again\n";
continue;
}
if ((value >= minAllowed) && (value <= maxAllowed)){
break;
}
std::cout << "not an allowed integer, enter a value between " << minAllowed << " and " << maxAllowed << ".\n";
}
while (true);
return value;
}
int main(){
int max = promptForInt("What is the max?", -1000, 1000);
std::cout << "The max number of steps are " << max << std::endl;
return 0;
}

I am debugging this C++ program. There are no more syntax errors that compiler shows, but there are hidden logical errors

#include <iostream>
#include <iomanip>
using namespace std;
const int N = 20;
int main ()
{
//Declare variables
int counter; //loop control variable
int number; //variable to store the new number
int zeros = 0; //Step 1
int odds = 0; //Step 1
int evens = 0; //Step 1
int positives = 0;
int negatives = 0;
// Display Program Intro telling what the program does.
cout << "********************************************************"
<< "\n* This is a program that counts integers you enter as *"
<< "\n* even, odd or zero and positve or negative *"
<< "\n* It classifies 20 numbers or use 99999 to exit early *"
<< "\n********************************************************"
<< endl;
// Ask for 20 integers with 99999 as early exit
cout << "\n\nPlease enter " << N << " integers, "
<< "positive, negative, or zeros."
<< "\n\t\t or enter number 99999 to exit early. \n\n"
<< endl; //Step 2
cout << "The numbers you entered are:" << endl;
// Loop that classifies the numbers entered.
for (counter = 1; counter <= N; counter++) //Step 3
{
// Enter number and mirror it backed on a tabbed line.
cin >> number; //Step 3a
cout << number << endl; //Step 3b
// Early exit condition: 99999
if(number = 99999)
break; // Exit loop before 20 numbers
// Count Postive and Negative Numbers
if(number < 0)
negatives++;
else
positives++;
// Count Evens, Odds and Zeros
//Step 3c
switch (number % 2)
{
case 0:
evens++;
if (number == 0)
zeros++;
case 1:
case -1:
odds++;
} //end switch
} //end for loop
cout << endl;
// Display the results ....
//Step 4
cout << "There are " << evens << " evens, "
<< "which includes " << zeros << " zeros."
<< endl;
cout << "The number of odd numbers is: " << odds
<< endl;
cout << "The number of positive numbers is: " << positives
<< endl;
cout << "The number of negative numbers is: " << negatives
<< endl;
// Use Holdscreen to make sure the results are visible ....
char holdscr; // This character and section is to hold screen open
cout << "\n\n\tPress a character and Enter to exit program. ";
cin >> holdscr;
return 0;
}
I am debugging this program. There were originally 6 errors in the program. I've found four of them as they were syntax errors. The compiler doesn't show any error but the program isn't working either.
The program is supposed to store 20 numbers and in the end tell you how many of them were even, odd, zero, negative, and positive. I am just a beginner in C++. I have tried every possible way to solve it from my side but I cannot get it to work. I have looked up every code and syntax on Google why it works that way but found no help. Any help here would be highly appreciated.
If you enable warnings when you compile then the compiler will helpfully point out certain mistakes in your code, and if it's in a good mood it may even suggest a solution:
<stdin>:46:23: warning: using the result of an assignment as a condition without parentheses [-Wparentheses]
if(number = 99999)
~~~~~~~^~~~~~~
<stdin>:46:23: note: place parentheses around the assignment to silence this warning
if(number = 99999)
^
( )
<stdin>:46:23: note: use '==' to turn this assignment into an equality comparison
if(number = 99999)
^
Always compile with warnings enabled (e.g. gcc -Wall ...) - it will save you a lot of time and debugging effort in the long run.

c++ accepting 0 into while loop illegally

Here is the objective: "Write a c++ program which prompts the user to enter some numbers and finds the minimum, maximum, and count
(number) of the entered numbers separately for the positive and negative numbers. It then prints out this information
in the correct format. Entering 0 should terminate the input sequence and cause the results to be displayed.
My problem is, when I run the code through www.cpp.sh, it seems to be storing the 0 that I use to end the sequence to a maximum or a minimum variable (posmax and negmax or posmin and negmin). My while loop's condition is number_entered !=0, so 0 shouldn't even be going into the loop...
if the first 3 in the sequence are negative and the last 3 are positive; if the first 3 in the sequence are positive and the last 3 are negative
Stranger still, the 0 being stored as a minimum or negative only seems to happen to the last sequence of variables entered.
Relevant code:
int main()
{
double number_entered, posmax, posmin, negmax, negmin;
int positive_count, negative_count;
positive_count = 0;
negative_count = 0;
posmax = 0;
posmin = 0;
negmax = 0;
negmin = 0;
//before it goes into a loop it will do the following:
cout << "Entering 0 will terminate the sequence of values.\n" << endl;
cout << "Enter a number: ";
cin >> number_entered; //stores input to number_entered
if (number_entered > 0) //if positive
{
posmax = number_entered; //needs to be initialized before use in loop
posmin = number_entered; //needs to be initialized before use in loop
}
else if (number_entered < 0) //if negative
{
negmax = number_entered; //needs to be initialized before use in loop
negmin = number_entered; //needs to be intiialized before use in loop
}
while (number_entered !=0) //will keep looping as long as the while condition is true
{
if (number_entered > 0) //branch if number_entered is positive
{
if ( number_entered > posmax) //sub-branch to compare to get max
{
posmax = number_entered; //if number is larger than the current max, it gets stored as the new max
}
else if ((number_entered < posmin)||(posmin == 0)) //sub-branch to compare to get min; since posmin is initialized to 0 it needs to be updated
{
posmin = number_entered; //if number is less than min than it gets stored as the new min
}
positive_count++; //under main if branch for if the number is positive, add to positive_count
}
else if (number_entered < 0) //branch for if number_entered is negative
{
if ( number_entered > negmax) //sub-branch if number_entered is more than the max
{
negmax = number_entered; //it then gets stored as the new negmax
}
else if ((number_entered < negmin)||(negmin == 0)) //sub-branch if number_entered is less than min; since negmin is initialized to 0 it needs to be updated
{
negmin = number_entered; //it then gets stored as the new negmin
}
negative_count++;
}
cout << "Enter a number: "; //prompts for input again after it is done counting, and comparing to store a max and min
cin >> number_entered;
} //end of while loop
if (number_entered == 0)
{
cout << endl;
if ((negative_count > 0) && (positive_count > 0)) //for situations where it received both positive and negative values
{
cout << "There were " << negative_count << " negative values entered, with minimum "<< negmin << " and maximum " << negmax << endl << endl;
cout << "There were " << positive_count << " positive values entered, with minimum "<< posmin << " and maximum " << posmax << endl<< endl;
}
else if (negative_count > 0 && positive_count == 0) //for sitautions where only negative input was received
{
cout << "There were " << negative_count << " negative values entered, with minimum "<< negmin << " and maximum " << negmax << endl << endl;
cout << "No positive numbers were entered" << endl;
}
else if (positive_count > 0 && negative_count == 0) //for situations where only positive input was received
{
cout << "There were " << positive_count << " positive values entered, with minimum "<< posmin << " and maximum " << posmax << endl<< endl;
cout << "No negative numbers were entered" << endl;
}
else if (negative_count == 0 && positive_count == 0) //for if only 0 was received
{
cout << "No positive numbers were entered.\n"
<< endl
<< "No negative numbers were entered.\n"
<< endl;
} //end of nested branching if-else if statement
} //end of if statement
return 0;
}
I figured it out finally, but maybe I posted the answer badly and that was why I didn't get the answer I needed.
in order to get a max that wasn't 0 for the negative values, I simply needed to move my || (negmax == 0) condition to the correct if statement (it was on the minimum branch).
There were no other issues with the program.
Because your initial values are zeros. There is no way that you will enter number lower (for positives) and higher (for negatives) than zero.

C++ Random integer seems to always be the same

For my current project i have created an event that should change depending on the random integer my code generates, the only problem is that i seem to always be getting the same path. In short i want it to be a 50% chance of either event occurring.
Thanks, Simon
random1 = rand() % 1 + 0;
if (random1 == 0) {
int choice4;
cout << "Your character screams at the top of his lungs, " << endl;
cout << "this causes the dragon to immediately to bow in fear..." << endl;
cout << "It turns out dragons are very sensitive to hearing....." << endl;
system("pause");
cout << "\nIt seems the dragon is requesting you ride it!\n" << endl;
cout << "Will you ride it?\n" << endl;
cout << "1. Ride it" << endl;
cout << "2. Or Wait here." << endl;
cin >> choice4;
cin.ignore();
system("cls");
if (choice4 == 1){
Ending();
}
}
else if (random1 == 1) {
cout << "Your character screams at the top of his lungs, " << endl;
cout << "eventually your breath gives out and you die because of lack of oxygen." << endl;
system("pause");
gameover();
All other answers so far mention the need to use srand() to initialize your random number generator, which is a valid point, but is not the problem you're having.
Your problem is that your program computes the modulo of your random number and 1, which is always going to be equal to 0, because for any integer n,
n % 1 == remainder of the integer division of n by 1
== n - (n / 1)
== 0
So, replace this:
random1 = rand() % 1 + 0;
with this:
random1 = rand() % 2;
and you will have something that sort of does what you want. I'm saying "sort of" because there are other issues to consider, such as random number generator initialization (srand()), using rand() rather than more elaborate RNGs, etc.
rand() can only generate pseudo random numbers, that is, the same seed will generate same sequence.
just use srand() to initialize seed, here is an example
#include <cctype>
#include <sys/time.h>
struct timeval cur_tm;
gettimeofday(&cur_tm, NULL);
seed = static_cast<unsigned int>(cur_tm.tv_usec);
srand(seed);

New answer same number? C++

So I have this program:
#include <iostream>
using namespace std;
bool prime(int input)
{
// cout << "pinput: " << input << endl;
int i = ((input/2) + 1);
// cout << "pi: " << i << endl;
int c;
for (i>0; i--;){
//cout << "pi: " << i << endl;
if (input == 3 || input == 2){
// cout << "true" << endl;
return true;
}
if (input == 1){
// cout << "pi = 1" << endl;
return false;
}
c= input%i;
if (c==0 || i == 1 ){
// cout << "false" << endl;
return false;
}
else if (c!=0 && i<4){
// cout << "true" << endl;
return true;
}
}
return 0;
}
int factor(int input){
// cout << "finput: " << input << endl;
int i = (input/2) + 1;
int c;
int e;
bool d = false;
for (i>0; i--;){
// cout << "fi: " << i << endl;
c = input%i;
if (c==0){
d = prime(i);
if (d==true){
// cout << "found" << endl;
return i;}
}
if (i==1){
// cout << "fi = 1";
return 0;
}
//cout << "not prime" << endl;
}
return 0;
}
int main(){
int woot;
cout << "Please insert quater: " <<endl;
cin >> woot;
int answer;
answer = factor(woot);
if (answer == 0)
cout << "no prime factors" << endl;
else
cout << "answer is: " <<answer << endl;
return 0;
}
It seems to work until I put a really big number in like more specifically the number 600851475143, in which case I always get different answers when I run that number now I'm pretty sure it's just exceeding the size of it's variable type. Now then I was looking and I can't find the right variable type for a number that big, I int and long seem to be for numbers that are for numbers up to 4294967295 if unsigned however that is only 10 digits long, mine is 12. What type of variable should I use? Or will that even fix the problem? The program is to find the largest prime factor of a number (Euler problem 3). Any tips links or advice would be appreciated. And of course an answer extra appreciated! :D
Interesting typo alert!
This is unlikely to be doing what you think it is doing...
for (i>0; i--;){
While it is perfectly legal syntax, and will loop the correct number of times, the value of i inside the loop is (probably) going to be one less than you intended...
% cat 4237157.c++
#include <iostream>
int main()
{
{
std::cout << "Your loop: " << std::endl;
int i = 10;
for (i>0; i--;)
{
std::cout << i << std::endl;
}
}
{
std::cout << "More conventionally: " << std::endl;
for (int i = 10; i > 0; i--)
{
std::cout << i << std::endl;
}
}
return EXIT_SUCCESS;
}
% g++ -o 4237157{,.c++}
% ./4237157
Your loop:
9
8
7
6
5
4
3
2
1
0
More conventionally:
10
9
8
7
6
5
4
3
2
1
The syntax for a for-loop in C-like languages is:
for (variable initialization; conditional; variable increment)
You are evaluating "i>0" instead of doing any initalization. This may as well be blank. Then you are evaluating whether i-- is zero. Since i is post-decremented, your loop starts with i being one less than it was initialized with before the loop, executes until (and including) being equal to zero and then terminates.
A lot of the problems on Project Euler call for arbitrary-precision arithmetic, which isn't covered by the C++ standard library.
Have a look at the C++ Big Integer Library.
If you want arbitarily big numbers, you need an arbitary precision arithmetic library
unsigned long 4294967295
unsigned long long 18446744073709551615
unsigned long long is not standard C++, but most compilers support it as an extension. The maximum should be at least 2^64 - 1, which is more than enough.
If you later want even larger numbers, you can use a arbitrary precision library such as GMP. They have a C++ interface.