-1

So I wrote this code...

#include "pch.h"
#include <iostream>
#include <time.h>

int random(int a, int b);
int a;
int b;

int main()
{
printf("Hello and welcome. You will now solve the following multiplication\n\n");

printf("What is: %d * %d ??", random(a, b));

}


int random(int a, int b)
{

srand(time(NULL));
a = rand() % 10;

b = rand() % 10;

return a*b;
}

My question is, how do I take the value of "a" and "b" from "int random" and place them inside my printf in "main"? I want random numbers to be generated that I can print on my screen via a function. Any help is gladly appreciated!

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85

1 Answers1

2

You can use references to have functions modify caller's variables.

#include <iostream>
#include <ctime>

int random(int& a, int& b); // add & to make arguments references

int main()
{
    printf("Hello and welcome. You will now solve the following multiplication\n\n");

    int a, b;
    int ret = random(a, b);
    printf("What is: %d * %d ??", a, b);
    printf("\nIt is %d!\n", ret);
}


int random(int& a, int& b) // add & to make arguments references
{

    srand(time(NULL));
    a = rand() % 10;

    b = rand() % 10;

    return a*b;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • I am getting an answer with @MikeCAT 's answer. It says ... int ret = random(a, b); "More than one instance of overloaded function "random" matches the argument list" –  Oct 22 '20 at 15:06
  • @NemanjaVuksanovic Ouch, fixed the function declaration. – MikeCAT Oct 22 '20 at 15:07
  • Thank you so much @MikeCAT it is just what I wanted the program to do!!! May I ask what the "&" tells the computer to do? I see your comment says "... make arguments references" but could you maybe elaborate a little on it? Further more, because I need everything cut out on paper, what is the difference between a function having "&" and not having "&" in it's parameters? And what is is called when doing so? I know what it does in a scanf btw:)) –  Oct 22 '20 at 15:10
  • Copy of variables are passed without `&` and references (the place of the variables on caller) are passed with `&`. Google "C++ variable reference" and you will get more information. – MikeCAT Oct 22 '20 at 15:13