trying to create a dice game using function c++ - c++

i am trying to have a function determine the result
a. If the numbers add up to 5, 7, or 12, then the player wins, and the function should return an indication of this (use some integer to represent a win).
b. If the numbers add up to 2, 4, or 11, then the player loses, and the function should return an indication of this (once again, use an integer).
c. If the numbers add up to anything else, then the game is a draw and the function should say this (by way of an integer).
question, do i need a different func for winner, loser, and draw?
and what how can i return a integer to main to let main know that if we have a winner a loser a draw.
just learning to program any help would be greatly appreciated
//function
int outcome(int, int)
{
int die1;
int die2;
int winner;
int loser;
int draw;
if (die1&&die2==5||7||12)
return 99;
if (die1&&die2==2||4||11)
return loser;
else
return draw;
}
// func to get a random number
int rollDice()
{
int roll;
roll = (rand()%6)+1;
return roll;
}
the main func
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
int main()
{
double die1=0;
double die2=0;
int winner=0; //counter for winners
int loser=0; //counter for losers
int draw=0; //counter for draw
//func to determine the outcome
int outcome(int, int);
//func for random numbers
int rollDice();
int outcome(int, int)
if (return==99)
cout <<"winner";

Your code has several syntax errors. If I want to, say, make a function to add two integer numbers, I'd do something like this:
int add(int a, int b) //VARIABLES MUST CARRY A NAME!
{
return a+b;
}
If you want to work with conditions, do this:
if(a==5 && b==6 || a==6 && b==7) //Just as an example
Your fixed condition would be this:
if (die1+die2==5 || die1+die2==7 || die1+die2==12)
Also, study variable scope. Let's say I have the following:
int main()
{
int myVar = 1;
}
int anotherFunction()
{
println("%d", myVar); //This will cause an error, because myVar doesn't exist here, it only exists in main()
}
These are the most notable errors I can see in your code.

Related

No Output from Array Loop

I am to draw 3 balls from an urn of 24 and add up the total discount the balls represent. I am not allowed to replace the balls after drawing, so there can be no duplicate balls drawn. The discounts are 1, 2, 3, 4, 5, 6, 7, 8, and there are 3 of each.
My solution to this problem was to create multiple while loops that roll out of 24 and re-roll until no duplicates are drawn. I have done a loop like this in the past that would loop random numbers until a non-duplicate was chosen and it worked fine, so I set this program up the same way.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int draw(int urn[], int draws[]);
int main()
{
int discountSum,discount;
int urn[24]={1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8};
int draws[1000]={0};
draw(urn,draws);
cin >> discount;
int averageDiscount=discount/1000;
return 0;
}
int draw(int urn[], int draws[])
{
static int discountSum=0;
int i; //simulations counter
int ball1, ball2, ball3;
int score1, score2, score3;
int totalDiscount;
srand(time(0));
for(i=0;i<1000;i++)
{
ball1=rand()%24;
while (ball2==ball1)
{
ball2=rand()%24;
}
while ((ball3==ball2)||(ball3==ball1))
{
ball3=rand()%24;
}
score1=urn[ball1];
score2=urn[ball2];
score3=urn[ball3];
totalDiscount=score1+score2+score3;
draws[i]=totalDiscount;
cout << "1) " << draws[i] << " percent discount.\n";
discountSum+=totalDiscount;
}
return discountSum;
}
When I run this code, instead of receiving an error, the program runs with no output, and a return of a negative garbage value instead of 0. I would like to see the output from each discount up to the 1000th loop.
It looks as if the bug is that ball2 and ball3 are compared before they're ever set to anything. They're never even initialized, which is the likely cause of your "garbage value." It'll probably work if you "draw" each ball before comparing it, as:
ball1=rand()%24;
ball2=rand()%24;
while (ball2==ball1)
{
ball2=rand()%24;
}
ball3=rand()%24;
while ((ball3==ball2)||(ball3==ball1))
{
ball3=rand()%24;
}
An even better way would be to use do...while loops instead, which always run once, as:
ball1=rand()%24;
do
{
ball2=rand()%24;
} while (ball2==ball1);
do
{
ball3=rand()%24;
} while ((ball3==ball2)||(ball3==ball1));
A much simpler way to do this is to use the facilities build into the C++ standard library:
#include <iostream>
#include <algorithm>
#include <random>
std::mt19937 gen(std::random_device{}()); // initialize random number generator
/*
* or
std::mt19937 gen(std::time(NULL));
* if std::random_device is not well-implemented
*/
int draw()
{
static int urn[24]={1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8};
std::shuffle(std::begin(urn), std::end(urn), gen); // shuffle array
return urn [0] + urn[1] + urn[2]; // pick first three balls from array
}
int main()
{
int discount = draw();
// Use discount. For example,
std::cout << discount;
return 0;
}
Documentation:
std::mt19937
std::random_device
std::shuffle

Why does the program to find the largest number formed using elements of an array not work?

Visit https://www.interviewbit.com/problems/largest-number/ for the question...
Now I wrote the below code to solve the question (although I used an array to store the number, will do the storing in strings part later..)-
So in this algorithm, I basically used quicksort but with a twist, I changed the definition of greater than or lesser than of two numbers say X, Y such that if the number formed by using X first and Y second or XY is >= YX then greater than(X, Y) is true
In the present scenario, the code is giving runtime error, which I can't understand why, also after a bit of debugging as shown in the comments, still the answer is not coming as expected.
#include <iostream>
#include <vector>
#include <cmath>
#include <stdlib.h>
#include <time.h>
using namespace std ;
bool greaterthan(int a,int b)
{
int n1,n2,s1,s2;
n1=((int )log10(a))+1;
n2=((int)log10(b))+1;
s1=a*((int )pow(10,n2))+b;
s2=a + ((int )pow(10,n1))*b;
if(s1>=s2){return true;}
else{return false;}
}
int spartitions(vector<int >&B,int s , int e)
{
int pivot = B[e];
int pin =s;
int i;
for(i=s;i<=e;i++) //if i change this to i<e
{
if(B[pin]>=pivot)
{swap(B[pin],B[i]);
pin++;
}
// and add swap(B[pin],B[e]);
}
return pin-1; // and return pin here then it works but not give correct output
}
int prand(vector<int >&B,int s ,int e)
{
srand(time(NULL));
int n = rand()%(e-s+1)+s;
swap(B[n],B[e]);
int pin = spartitions(B,s,e);
return pin;
}
void qsort(vector<int >&B,int s, int e )
{
if(s<e){
int p= prand(B,s,e);
qsort(B,s,p-1);
qsort(B,p+1,e);
}
}
vector<int> largestnumber(vector<int >&A)
{
int n =A.size();
vector<int >B(n);
B=A;
qsort(B,0,n-1);
return B;
}
int main()
{
int n;
cin>>n;
vector<int>A(n);
int i;
for(i=0;i<n;i++)
{
cin>>A[i];
}
vector<int >B(n);
B=largestnumber(A);
for(i=0;i<n;i++)
{
cout<<B[i];
}
}
Please Help as I am a newbie in programming and can't figure this out from like 3-4 hours ...??
Would really appreciate if someone can correct my code only and not give a different algorithm, as I want this algorithm to be corrected.
Your self-written qsort function recursively calls itself, which adds more things to the stack, which only has so much space. When the list is too big, there will be too many function calls in the stack and it overflows. That's why anything less than 5 for the first input (which is for n) works fine but as soon as you exceed that, you get a runtime error. Consider not using a recursive function call.
Edit: Enabling optimisation also seems to fix this issue.
This may not work depending on the compiler and how it optimises. (Works on MSVC)

Count the occurence of a particular digit in a range of number

I was trying to count the number of digit 2 in an range of number (say 2-22, the answer would be 6: 2,12,20,21,22 as 22 contribute twice). This is the code that I came up with, yet it fails to run after value input. Any ideas?
#include <iostream>
#include <cstdio>
using namespace std;
int main(){
int lowerbound,upperbound,sum=0;
int nofNum(int num);
scanf("%d %d",&lowerbound,&upperbound);
for (int i=lowerbound;i<=upperbound;++i){
sum+=nofNum(i);
}
printf("%d",sum);
return 0;
}
int nofNum(int num){
int count=0;
while(num!=0){
if (num%10==2){
count++;
num/=10;
}
}
return count;
}
you are using c not c++. Your mistake is that nofNum wasn't declared before you used it. It has to be declared before the line you use it.
int nofNum(int num);
would declare it.
You will still need to implement it, which you allready did.
alternatively you can move the implementation st. it is above main, where you used it.
EDIT: i just saw you declared it inside main, which is uncommon at best. you really should not do that.
EDIT2:
you messed up that if statement in numOf
int nofNum(int num){
int count=0;
while(num!=0){
if (num%10==2){
count++;
}
num/=10; // may not be inside if, since num would not be adjusted
// if the last digit isnt a 2
}
return count;
}
EDIT3:
you can use input and output streams in c++ to replace scanf and printf:
scanf("%d %d",&lowerbound,&upperbound);
becomes
std::cin >> lowerbound >> upperbound;
and
printf("%d",sum);
becomes
std::cout << sum << std::endl;
Edit4:
suggested form:
// declarations - this is what would belong to the *.h file later on.
int nofNum(int num);
followed by
int nofNum(int num) { /*implementation*/ }
int main(int /*argc*/, char* /*argv*/[]) { /*implementation*/ }
or
// this is valid because we allready heard of nofNum through declaration
int main(int /*argc*/, char* /*argv*/[]) { /*implementation*/ }
int nofNum(int num) { /*implementation*/ }
the upper form doesn't require the declarations because each function allready is implemented before you use them, therefore the compiler allready knows what nofNum is supposed to be.

Hello, This simple C++ script pops out an error at line 11. Does anybody know how to fix it?

Description
This code is intended to find a spanner index (i) when dealing with
Splines/NURBS basis functions based on a knot vector (U), a choosen knot (u), the degree of the desired curve (p) and the number of basis funcions (n). The algorithm was taken from the NURBS Book by Piegl and Tiller. The error, I guess, is in the way I declared variable U. Thaks in advanced!
code
# include <iostream>
using namespace std;
int n=3;
int p=2;
double u=5/2;
int U[11]={0,0,0,1,2,3,4,4,5,5,5};
int FindSpan(n,p,u,U) /* an error in this line */
{
if (u==U[n+1]) return (n);
low=p; high=n+1;
mid=(low+high)/2
while(u<U[mid] || u>=U[mid+1])
{
if (u<U[mid]) high=mid;
else low=mid;
mid=(low+high)/2
}
return (mid);
}
You have forgotten some semicolons and types!
here is the correct code:
#include <iostream>
using namespace std;
int n=3;
int p=2;
double u=5/2;
int U[11]={0,0,0,1,2,3,4,4,5,5,5};
int FindSpan(int n, int p, int u, int U[])
{
if (u==U[n+1]) return (n);
int low=p, high=n+1;
int mid=(low+high)/2;
while(u<U[mid] || u>=U[mid+1])
{
if (u<U[mid]) high=mid;
else low=mid;
mid=(low+high)/2;
}
return (mid);
}
int main() {
cout << FindSpan(n, p, u, U);
return 0;
}

Id returned 1 exit status. C++

I'm very new to C++, so I've probably made some really stupid mistakes. But I've looked online to solutions for this error, and I tried all I can think of.
I'm trying to have my whole program in one function, because it's going to be merged with other programs. The id error is the only error I have so far.
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
using namespace std;
int ninebooking(int Endor=0, int Naboo=0, int tatooine=0);
int sevenbooking(int Endor=0, int Naboo=0, int tatooine=0);
void BookingSystem(int time, int k);
int time;
int k = 0;
int main()
{
BookingSystem(time, k);
{
while (k==0)
{
printf("\n\nMeals are served at 9pm and 7pm, please enter what time you would like to book for");
scanf("You have selected to book your meal for %d", &time);
if (time!=7||time!=9)
{
printf("Sorry, that was an incorrect time");
time = 0;
}
}
return 0;
}
system ("pause");
return 0;
}
Any help is much appreciated, I've spent a long time trying to fix this on my own with no luck.
Thank you!
You make many mistakes in your program:
1) You mix C & C++ syntax.
using namespace std, is C++
2) You include useless header files
3) You declare variables that I don't understand what for
Why do you need this?
int ninebooking(int Endor=0, int Naboo=0, int tatooine=0);
int sevenbooking(int Endor=0, int Naboo=0, int tatooine=0);
You don't use the variables above anywhere !!!!
4) You try to write a function inside main (this is not Pascal).
So, if I understand what you want, look at this:
#include <stdio.h>
void BookingSystem() // this is the function who does all job
{
int time = 0;
while ((time != 7) && (time != 9))
{
printf("\n\nMeals are served at 9pm and 7pm, please enter what time you would like to book for");
printf("\nYou have selected to book your meal for ");
scanf("%d", &time); // read the time
scanf("%*[^\n]"); // consume all caracters until the newline
scanf("%*c"); // consume the newline
if (time == 7)
{
printf("You have selected to book your slot at 7PM\n");
}
else if (time == 9)
{
printf("You have selected to book your slot at 9PM\n");
}
else
{
printf("You have selected an incorrect time, please try again\n");
}
} // end while
} // end function
int main(int argc, char *argv[])
{
BookingSystem(); // this is the calling to your function
return 0;
}
If I understand what you want, this works fine.
you can not to Define Function in to the main ..
you must to do like this...
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
using namespace std;
int ninebooking(int , int , int ); //just say data type int or ....
int sevenbooking(int , int , int );
void BookingSystem(int , int);
int main() //and in to main just call he...
{
int time;
int k = 0;
BookingSystem(time, k);//call ....and send parameter time and k
system ("PAUSE");
return 0;
}
void BookingSystem(int time,int k)
{
while (k==0)
{
printf("\n\nMeals are served at 9pm and 7pm, please enter what time you would like to book for");
scanf("You have selected to book your meal for %d", &time);
if (time!=7||time!=9)
{
printf("Sorry, that was an incorrect time");
time = 0;
}
}
// return 0;//if this function is void he can not to return any thing!!!!
}
int ninebooking(int Endor=0, int Naboo=0, int tatooine=0)
{
//......
}
int sevenbooking(int Endor=0, int Naboo=0, int tatooine=0)
{
//........
}