Okay, so I'm learning C++ with my friend, and our section of code isn't working:

Code:
#include <stdio.h>     
#include <stdlib.h>     
#include <time.h>       

int main ()
{
  srand (time(NULL));
  printf ("Random number: %d\n", rand()%100);
  srand (1);
  return 0;
}

This is what the output looks like:
    Random number: 27, Random number: 27, Random number: 84, Random number: 15, Random number: 15

And so on. I know it's pseudo-random, but it still doesn't seem... random at ALL. Any ideas?
Haha, looks to me like you guys are actually learning the C style, not the C++ style. This is more what should work. Remember, numbers aren't "random", as in 1,2,3,4,5,6 could be random, it just doesn't look chaotic.


Code:
#include <iostream>       
#include <cstdlib>     
#include <ctime>       

int main ()
{
  srand(time(NULL));
  std::cout << "Random number: " << rand()%100;
  return 0;
}
Oh, really? Hmmm... And, also, what does that std :: do?
It means it is in the std namespace. As for learning C before C++; I think it is justified. The adage:
Quote:

One should learn to crawl before one walks

goes quite well with this idea.
Also the:

Code:

srand(1);

is unneeded. It has no effect on your code. What that does is set an internal seed to the value of one. You do not generate any more pseudorandom numbers, thus setting the seed was a waste. Also you do not want to set the seed each time you generate a pseudorandom number.
gaven: It references a member of the std namespace.

MateoConLechuga wrote:
Haha, looks to me like you guys are actually learning the C style, not the C++ style. This is more what should work. Remember, numbers aren't "random", as in 1,2,3,4,5,6 could be random, it just doesn't look chaotic.


Code:
#include <iostream>       
#include <cstdlib>     
#include <ctime>       

int main ()
{
  srand(time(NULL));
  std::cout << "Random number: " << rand()%100;
  return 0;
}


You're missing a << std::endl; or things will get a little whacky Smile
elfprince13 wrote:
You're missing a << std::endl; or things will get a little whacky Smile

Oh yeah. Smile Meh, it just won't go to the next line. Should be okay on Unix or something like that. Smile But yes, do that as well.

And I do think that C is a much better language to learn first, as it makes a lot more sense before you get more into OOP programming. C also has a ton of applications in the real world, especially on platforms where C++ isn't really an option.
Disregarding C vs C++ things, I'd guess you're seeing duplicate values in the "random" output because you're running the program more than once a second.

The resolution of time(3) is only down to seconds, so running the program multiple times when that function returns the same value will seed the RNG with the same value, thus generating the same sequence.

rand(3) is all around a bad source of randomness. drand48 and friends are significantly nicer, though I have no idea if MSVC and such support it since they're specified by POSIX.
MateoConLechuga wrote:
elfprince13 wrote:
You're missing a << std::endl; or things will get a little whacky Smile

Oh yeah. Smile Meh, it just won't go to the next line. Should be okay on Unix or something like that. Smile


This will

  1. make your shell look whacky on exit,
  2. generally prevent you from seeing output until the program exits (or not at all if it crashes). Writing a newline generally causes I/O to flush, but writing normal characters typically does not.


Not the end of the world, but useful to know about.
Okay , thanks! That makes sense... sort of...
A question of primes:

Code:

#include <iostream>

using namespace std;

int main()
{
   for(int c = 0; c<10; c++) {
       int p=1;
       cout <<c;
       for(int i = 1; i<c; i++) {
           if (c%i == 0) {
               p=0;
           }
       }
       if (p == 1) {
           cout <<" is prime.";
        }
        cout <<endl;
   }
   
   return 0;
}


This returns 0 is prime and 1 is prime. I'm pretty sure that's a LITTLE off. Ideas why?

EDIT: Oop, never mind! I should start as 2, not 1! Duh!
There's no reason for your inner loop to go above sqrt(c)
Right. I was just trying to make sure I got the right syntax for now, not really optimizations and speed and such.
I do thank you, though!
Can somebody give me some pointers about the point of pointers? XD
Seriously, aren't pointers just like variables, but their addresses? What's the point of them? Why cant we use variables all the time?
Pointers are the way that the computer reads the code. They don't see pointers as a bunch of letters that form words, but rather numbers that tell them where the information is stored. People just give them a name, in which the compiler translates to those numbers instead when you run a program. At least, I think this is how they work?
I know what they are, I just don't get their PRATICAL uses. Why not use variables all the time, why do we need to know their location?
Arrays and pointers are interchangeable. At least at that level, pointers are required.

Code:
// Compute the sum of values in `a` and `b`, writing to `c`.
void sum(int *a, int *b, int *c, size_t n) {
    while (n--)
        *c++ = *a++ + *b++;
}

Alternate:

Code:
void sum(int *a, int *b, int *c, size_t n) {
    for (size_t i = 0; i < n; i++) {
        c[i] = a[i] + b[i];
    }
}

The not-so-sane way to dereference:

Code:
void sum(int *a, int *b, int *c, size_t n) {
    for (size_t i = 0; i < n; i++) {
        i[c] = i[b] + i[a];
    }
}


All of these are equivalent. There are other practical considerations for when you might need a pointer, mostly relating to performance of large copies in function calls.
gaventemples31415 wrote:
I know what they are, I just don't get their PRATICAL uses. Why not use variables all the time, why do we need to know their location?


There are a couple good reasons:


  1. If you're dealing with large datastructures, you don't want to have copy them all onto the stack, you just want to be able to say "I already have this data saved somewhere else, look over here"

    Code:

    struct ExampleA{
    long lots;
    long of;
    long data;
    long is;
    long stored;
    long in;
    long here;
    }
    long badlybehaved(ExampleA ex){
      return ex.lots + ex.data;
    }
    long betterbehaved(ExampleA *ex){
      return ex->lots + ex->data; // or *ex.lots + *ex.data
    }
    long bestbehaved(const ExampleA *ex){ // We aren't going to change ex, so promise that to the compiler, and it will allow it to make various optimizations
      return ex->lots + ex->data;
    }


  2. If you want to get multiple "return" values out of a function:

    Code:

    void divandmul(float a, float b, float *ret1, float *ret2){
      *ret1 = a * b;
      *ret2 = a / b;
    }


    Code:

    bool divideOrFail(float a, float b, float *ret){
      if(b == 0){
        return false;
      } else {
        *ret = a /b;
        return true;
      }
    }




Of course, C++ allows reference variables, which serve a similar purpose to pointers, but are generally a little safer, because they must be initialized to meaningful values (and a little more convenient because you don't have to remember to use -> vs ., it's just . like with non-pointer classes and structs) .
gaventemples31415 wrote:
I know what they are, I just don't get their PRATICAL uses. Why not use variables all the time, why do we need to know their location?


Also, see memory mapped IO and memory mapped file IO. With pointers, you can, say, send bytes to a buffer in a UART peripheral (starting at 0x44E09000 for Cortex ACool, access shared/mapped memory, pass around references to unknown data, allocate memory, trash the stack, manipulate the stack, etc.. pointer to pointer and pointer to pointer to pointer can get interesting when you want to return values or manipulate caller variables.

Pointers are very powerful with loads of uses.

(Tari++ for the not-so-sane deref. method)
  
Register to Join the Conversation
Have your own thoughts to add to this or any other topic? Want to ask a question, offer a suggestion, share your own programs and projects, upload a file to the file archives, get help with calculator and computer programming, or simply chat with like-minded coders and tech and calculator enthusiasts via the site-wide AJAX SAX widget? Registration for a free Cemetech account only takes a minute.

» Go to Registration page
Page 1 of 1
» All times are UTC - 5 Hours
 
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum

 

Advertisement