rand() function generates the next number by ascending to the previous number - c++

Please check code given below. The random number it generates for each execution is the increment of the previous generated number in the previous execution.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
srand(time(NULL));
cout<<"\n Random Number : "<<rand()<<endl;
cin.get();
return 1;
}
Please executeit for 5-6 times and you will see that the random numbers are increasing for each execution and they are very close to each other.
Note : Please use CodeBlocks or Visual studio to check it, not the online compilers.

Actually I found a way to solve my problem but still it might not be an answer to my question.
Anyway the problem is not about srand() or rand() functions but it is about the function time(NULL). Since I am trying to run this code on Windows, instead of using time(NULL) as a parameter for srand(), I used GetTickCount() and now it generates random numbers properly for each execution.
#include <iostream>
#include <cstdlib>
#include <windows.h>
using namespace std;
int main()
{
srand(GetTickCount());
cout<<"\n Random Number : "<<rand();
cout<<"\n";
cin.get();
return 1;
}

Related

clang++ compiler is hanging with -std=c++17 -O3

I am using this command line to compile my program.
clang++ -std=c++17 -O3 main.cpp -o main
I have started the compiler 20 minutes ago, and it is just hanging. I terminate the compiler, and try to compile it again and it is still hanging. If I use the exact same command line, but without the -O3 the compiler completes instantly, but with the -O3 it is hanging.
The code that it is compiling is relatively simple, without any errors. What is going on?
#include <ctime> // for time()
#include <cstdlib> // for srand(), rand(), size_t, EXIT_SUCCESS
#include <iostream>
#include <string>
#include <vector>
using std::cout;
using std::endl;
using std::string;
using std::vector;
int main()
{
vector<string> messages;
messages.push_back(string("“Blessed are those who are persecuted because of righteousness, for theirs is the kingdom of heaven.”"));
messages.push_back(string("“Let the little children come to me, and do not hinder them, for the kingdom of heaven belongs to such as these.”"));
/* Literally 10000 more quotes from the Bible. */
srand(time(NULL));
cout << messages[ rand() % messages.size() ] << endl;
return EXIT_SUCCESS;
}
What is going on?
If you want to keep all the strings in the program (instead of reading them from a file) I would replace the std::vector<std::string> with a const std::vector<std::string_view> or maybe even a const std::vector<const char*> and initialize it with all the strings:
#include <ctime> // for time()
#include <cstdlib> // for srand(), rand(), size_t, EXIT_SUCCESS
#include <iostream>
#include <string_view>
#include <vector>
int main() {
const std::vector<std::string_view> messages{
"“Blessed are those who are persecuted because of righteousness, for theirs is the kingdom of heaven.”",
"“Let the little children come to me, and do not hinder them, for the kingdom of heaven belongs to such as these.”",
/* Literally 10000 more quotes from the Bible. */
};
srand(time(NULL));
std::cout << messages[ rand() % messages.size() ] << '\n';
}
I wasn't patient enough to wait for the compiler to finish compiling your original code. The above compiled in ~1 second.
Note: There's a <random> header which gives you access to much better pseudo random number generation than rand(). You should look into using that instead. The end of your program would look like something like this using that:
std::mt19937 prng(std::random_device{}());
std::uniform_int_distribution<std::size_t> dist(0, messages.size() - 1);
std::cout << messages[ dist(prng) ] << '\n';

Netbeans C++ Weird output

#include <iostream>
using namespace std;
int main(){
cout<<"Hello World!"<<endl;
}
I recently installed netbeans 12.0 and when I compile the code above, it says some weird words and numbers and a letter 'H'.
Also the words using, namespace, cout, and endl are underlined and when I hover to it, it says:
unable to resolve identifier + 'word'
This is the output:
PSID=1493
NBMAGIC=1492
H
RUN SUCCESSFUL (total time: 101ms)
As #user4581301 specified that the programs runs and immediately quits so you are not able to see anything. So, we need something to pause the program.
#include <iostream>
using namespace std;
int main(){
cout<<"Hello World!"<<endl;
system("pause");
}

Unexpected value using random number generator as a function in C++

C++ beginner here with a problem using a functions. Please help!
I am trying to make a random number generator function that I can call from within int main to cout a randomly generated float between 0.0 and 1.0 to my screen. When I create the generator in int main and cout it runs fine and returns a float just the way I want, but when I put the same code in a function and call it in int main I get some mix of letters and numbers that makes no sense.
I understand that I could just use the code in the way it works and ignore it but at this point I really want to know why it's not working the way I'm trying to make it work. I've looked all over for the answer and feel as if I'm missing some really basic knowledge about the way functions work in C++.
Why is the code that works perfectly fine in int main returning gobbledygook when called from a function?
Random number generator in function (returns nonsense):
#include <iostream>
#include <random>
#include <ctime>
using namespace std;
float roll();
int main(){
cout<<roll<<endl;
system("PAUSE");
return 0;
}
float roll(){
default_random_engine generator;
uniform_real_distribution<float> distribution(0.0f,1.0f);
return distribution(generator);
}
Random number generator in int main (this one returns a float):
#include <iostream>
#include <random>
#include <ctime>
using namespace std;
int main()
{
default_random_engine generator;
uniform_real_distribution<float> distribution(0.0f,1.0f);
float roll = distribution(generator);
cout<<roll<<endl;
system("PAUSE");
return 0;
}
This is wrong:
cout<<roll<<endl;
You want:
cout<<roll()<<endl;
You want to call the function.
You just put the name of function which means just the address of it. Call it by using as defined.
For more information please check the tutorial.
#include <iostream>
#include <random>
#include <ctime>
using namespace std;
float roll();
int main(){
cout<<roll();<<endl;
system("PAUSE");
return 0;
}
float roll(){
default_random_engine generator;
uniform_real_distribution<float> distribution(0.0f,1.0f);
return distribution(generator);
}

How to get my program to output all values of the array Numbers to a file

I am trying to create a lottery program within c++ and the issue i'm having is attempting to output all values of the Numbers array into a file, however when i run the code, the only thing that gets outputted is the first set of values i put in, however the program allows me to type in more than one set. (The program allows for up to 6 sets of data), however it only outputs one.
Here is all my code
LotteryData.cpp
LotteryData::LotteryData()
{
}
LotteryData::~LotteryData()
{
}
void LotteryData::PassInfo(int (&Numbers)[6][6], int &NumberofGames)
{
ofstream Numfile;
while(NumberofGames>0)
{
Numfile.open("Numbers.txt");
for (int j=0; j<6; j++)
{
Numfile << Numbers[NumberofGames][j];
}
NumberofGames = NumberofGames - 1;
Numfile.close();
}
}
Player.h
#pragma once
#include <iostream>
#include <fstream>
using namespace std;
class Player
{
private:
public:
Player();
~Player();
void Input();
int Numbers[6][6];
int NumberofGames;
};
main.cpp
#include <iostream>
#include "Lottery.h"
#include "Player.h"
#include "LotteryData.h"
using namespace std;
int main()
{
Player player;
Lottery random;
LotteryData data;
player.Input();
random.setRandomNumber();
data.PassInfo(player.Numbers, player.NumberofGames);
}
Im not exactly sure where the problem is coming from but i think it may be from one of the pointers although not entirely sure.
Any help on this problem would be much appreciated.
Cheers
Edit: I've Changed the code within the PassInfo function within LotteryData.cpp file as #ali suggested
Edit2: I've cut down on the code as to where I think the problem occurs but as all of the code compiles, Visual Studio 2012 doesnt point to any actual errors in the program
In the while loop in the PassInfo function you are not changing the value of NumberOfGames. Therefore in the for loop you are using the same row of your Numbers array. You need another for loop to change the index for the first index of the Numbers[][] array.

srand(time(NULL)) "Function 'srand' could not be resolved."

I have been trying to debug this problem for a while and quite honestly, I just can't see what I'm doing wrong.
Why is there a syntax error?
#include <iostream>;
#include <time.h>;
#include <stdio.h>;
#include <stdlib.h>;
using namespace std;
class Problem3 {
public:
bool isPrime(long double num) {
srand(time(NULL));
return 0;
}
};
The error I'm getting is,
"Function 'srand' could not be resolved."
I'm well aware now that I don't need the semi-colons after 'include' statements
I'm using Eclipse CDT along with MinGW as my compiler
How I resolved the problem:
It had to do with the MinGW compiler I was using. Switching over to Visual Studio solved the problem.
; at the end of the #include directives are the problem in your code. #include directives don't need (wrong to place indeed) semicolons at the end unlike C++ statements.
[Warning] extra tokens at end of #include directive [enabled by default]
It seems any character after > in the directive causes this error/warning.
#include<iostream>a //error
Change to this:
#include <iostream>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
class Problem3 {
public:
bool isPrime(long double num) {
srand(time(NULL));
return 0;
}
};
int main(){
cout<<"Hello Main";
}
EDIT:
Regarding the linker issue:
One suggestion is C++ expects types to be explicitly casted between types (more than C). So, use a cast to convert time_t which is returned by the time to unsigned int which is the input parameter type of srand. (And of course this might not be the problem with linker error)
Instead of using stdlib.h, try using <cstdlib>, try if it helps. Because it uses namespace.
Apart from that, I have seen this snippet here. Use that pattern if it helps.
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
srand(time(0)); //use current time as seed for random generator
int random_variable = rand();
cout << "Random value on [0 " << RAND_MAX << "]: "
<< random_variable << '\n';
}
there is already question in SO check if that helps Eclipse Method could not be resolved in a simple program C++
Never use time() to initialize srand()..
EDIT:
Now it seems many people got this kind of problem. I found a question How do I fix Eclipse CDT Error “Function 'isdigit' could not be resolved. He is facing the same problem. The asker suggested a work around to this in his question edit.
Quoted from that question:
I now believe this to be a Code Analysis problem. A better solution is
to edit the Code Analysis options to make "Function could not be
resolved" be a warning instead of an error. That way you can see the
warnings in Problems view, but continue to work. If the function is
REALLY missing, the compiler will tell you! I also have a new theory,
that the problem is with the Code Analyzer following symlinks, because
all of the "missing" functions are in symlinked include files. Would
love any input on this theory.
Hope that points to solve the problem.
; should not be there after #include.
#include <iostream>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include files shoule not end with ;