int main(){
srand(time(0));
int numOfTimes;
int randNum;
int oneRoll = 0, twoRoll = 0, threeRoll = 0, fourRoll = 0, fiveRoll = 0, sixRoll = 0;
int onePercent, twoPercent, threePercent, fourPercent, fivePercent, sixPercent;
int count = 0;
cout << "How many times would you like to roll the dice?\n";
cin >> numOfTimes;
while (numOfTimes <= 0){
cout << "Invalid entry enter a number greater than 0\n";
cout << "How many times would you like to roll the dice?\n";
cin >> numOfTimes;
}
while (count < numOfTimes)
{
randNum = rand() % 6 + 1;
switch (randNum)
{
case 1:
oneRoll++;
break;
case 2:
twoRoll++;
break;
case 3:
threeRoll++;
break;
case 4:
fourRoll++;
break;
case 5:
fiveRoll++;
break;
case 6:
sixRoll++;
break;
default:
cout << "\n";
}
count++;
}
onePercent = (int)((oneRoll*100.0) /numOfTimes);
twoPercent = (int)((twoRoll*100.0) / numOfTimes);
cout << " # Rolled # Times % Times" << endl;
cout << "--------- -------- --------" << endl;
cout << "1 " << oneRoll << " " <<double (onePercent) << endl;
cout << "2 " << twoRoll << " " << "" << endl;
cout << "3 " << threeRoll << " " << ""<< endl;
cout << "4 " << fourRoll << " " <<"" << endl;
cout << "5 " << fiveRoll << " " <<"" << endl;
cout << "6 " << sixRoll << " " <<"" << endl;
I need it to print out the the one percent as a double. So I converted it as an int then to a double so it only prints two zeros like this (14.00) but its not converting at all its only printing 14
The main problem, just as Barmar mentioned in his comment, is that although you want the value to be printed to 2 decimal points, you round off the number in onePercent when you do:
onePercent = (int)((oneRoll*100.0) /numOfTimes); // Casting to "int" rounds off the number
Also, the declared data type for onePercent is int from the start:
int onePercent, twoPercent, threePercent, fourPercent, fivePercent, sixPercent; // onePercent is an "int" here
So you don't need a typecast of int, because you're casting an int to an int.
Therefore, even if you print onePercentwith 2 decimal-point precision, you will always get .00 as a result.
I would recommend taking off the (int) cast from that expression itself, and changing the initial data type of onePercent to type double. If you do not want to change the data types for the other variables declared alongside onePercent, then declare onePercent as a double on another line. That way, the precision of the value after the calculation will be maintained, and you will be able to output it to 2 decimal places.
As an aside, to specify the number of decimal places to output, the setprecision() function can be used:
cout << setprecision(2) << ... << endl; // The value passed to "setprecision" is up to you.
Related
its a text based monopoly game where i need the dice to select the number from the array like on a board.
I have the number generator, what i need to do though is when the value comes up it pluses it on the array to get the matching number so for example if the players rolls a 6, the 6 + array 0 = array value 6 which will be a name of a street but it means the player knows which place on the made up board they are on. here is the coding i am using to try and do so but i keep on getting 006ff65 what ever. i how can i get it for showing just the number as the names will be added later.
{
int main()
{
int number = 12;
int rnum = (rand() % number) + 1;
int house = 1;
int moneyscore = 10000;
double values[] = {
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40 };
char name[50];
cout << "Who are you, Dog, Car, Hat or Bus" << endl;
cin.getline(name, 50);
cout << "Welcome to Our Game " << name << " You have " << moneyscore << " .PLease Roll dice to get started" << endl;
cout << "\n----------------------Press any Enter to roll dice----------------------" << endl;
system("cls");
int choiceOne_Path;
cout << "# You roll a " << rnum << endl;
rnum = values[rnum];
cout << "# you have " << moneyscore << endl;
cout << "# You move to grid "<< values << endl;
cout << "\t >> Enter '1' Buy Property" << endl;
cout << "\t >> Enter '2' Recieve Rent" << endl;
cout << "\t >> Enter '3' End turn" << endl;
retry:
cout << "\nEnter your choice: ";
cin >> choiceOne_Path;
if (choiceOne_Path == 1)
{
cout << "\n Buy Property " << endl;
cout << " " << name << " has " << moneyscore << endl;
cout << " " << house <<" House has been placed by " << name <<" who spent 2,500" << endl;
moneyscore -= 2500;
cout << " " << name << " now has " << moneyscore << endl;
cout << "\n Roll again" << endl;
cout << "# You roll a " << rnum << endl;
}
else if (choiceOne_Path == 2)
{
cout << "\n You recieved 2500 from rent" << endl;
moneyscore += 2500;
cout << " " << name << "\n now has" << moneyscore << endl;
cout << "\n(Player will gain money form house, will need to find a way in order to make the
console remember what score == to postion)" << endl;
cout << "Ends turn" << endl;
}
else if (choiceOne_Path == 3)
{
cout << "\n Roll again" << endl;
cout << "# You roll a " << rnum << endl;
}
else
{
cout << "You are doing it wrong, player! Press either '1' or '2', nothing else!" << endl;
goto retry;
}
cout << "\n----------------------Press any key to continue----------------------" << endl;
_getch();
}
}
As far as I know, you should use srand (time(NULL)); between every call to rand() to correctly return a new random number from every call.
"srand" initialize the random number generator using a seed. In this case seed is time, which should be different on every call.
Pretty basic. You either made a few typos or need to learn how arrays work (and program flow, and subroutines, but perhaps that is for later lessons.)
First you are assigning the result of the array lookup back into your random number: rnum = values[rnum]; which is not a big deal except you use that variable later and it no longer contains what you may think it does. It actually contains the value you are looking for!
Second the variable values is a pointer to the head of your array so you are outputting the address of the values array with this line: cout << "# You move to grid "<< values << endl; there is no array look up happening at all here. It is strange you missed that because you did reference the array contents properly when you replaced the random number value earlier.
#include <iostream>using namespace std;
const int LIMIT=10;
int main () {
float counter;
int number=0;
int zeros=0;
int odds=0;
int evens=0;
cout << "Please enter " << LIMIT << " integers, " << "positive, negative, or zeros." << endl;
cout << "The numbers you entered are:" << endl;
for (counter=1; counter <=LIMIT; counter++) {
cin>>number;
switch (number / 2) {
case 0: evens++;
if (number=0) zeros++;
case 1: case -1: odds++;
}
}
cout << endl;
cout << "There are " << evens << " evens, " << "which includes " << zeros << " zeros." << endl;
cout << "The number of odd numbers is: " << odds << endl;
return 0;
}
Hi All,
I have a varsity question which has had me stumped all day. I need to amend the above script to allow me to enter 10 variable integers and the program must return me the total number of even numbers, total number of odd numbers and total number of zeros.
I have tried multiple solutions including (number % 2 == 0) in order to make my cases work under my switch parameter however I am missing something.
Please can someone assist pushing me into the right path.
(I know i need to remove the negative case but I wanted to post the raw code incase I take something out or ammend something that is needed)
#include <iostream>using namespace std;
const int LIMIT=10;
int main () {
float counter;
int number=0;
int zeros=0;
int odds=0;
int evens=0;
int n=0;
cout << "Please enter " << LIMIT << " integers, " << "positive, negative, or zeros." << endl;
cout << "The numbers you entered are:" << endl;
for (counter=1;
counter <=LIMIT;
counter++) {
cin>>number;
n=(number%2);
switch (n) {
case 0: evens++;
if (number==0) zeros++;
break;
case 1: odds++;
}
}
cout << endl;
cout << "There are " << evens << " evens, " << "which includes " << zeros << " zeros." << endl;
cout << "The number of odd numbers is: " << odds << endl;
return 0;
}
Thanks to papagaga managed to get it working - i think i was far too tired :)
std::vector<int> myvec = {0, 2, 3, 5, 0, 0, 5, 4, 9};
std::vector<int> zeros;
std::vector<int> evens;
std::vector<int> odds;
for (auto i : myvec) {
if (i % 2 == 0) {
if (i == 0) zeros.push_back(i);
else evens.push_back(i);
}
else
odds.push_back(i);
}
std::cout << zeros.size();
std::cout << evens.size();
std::cout << odds.size();
return 0;
}
If you don't want zeros to be in the evens vector, this will work.
Hello I'm beginning to learn c++ , I don't understand how enum works that well and I need help knowing how can I make the rand() working with enum
#include <iostream>
#include <cstring>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
cout << "First part : Create an item. " << endl;
int choice;
int Fire = 25;
int Water = 23;
int Wind = 24;
int Earth = 20;
int WeaponNature = 0;
enum NatureWeapons { Fire, Water, Wind, Earth}; // enum here if its wrong pls let me know ):
cout << "Enter the nature of weapon you want : " << endl;
cout << " 1 - Fire " << endl;
cout << " 2 - Water " << endl;
cout << " 3 - Wind " << endl;
cout << " 4 - Earth" << endl;
cin >> choice;
switch(choice)
{
case 1:
cout << "You picked fire."
cout << " Power : " << Fire << endl;
WeaponNature = Fire;
break;
case 2:
cout << "You picked water." << endl;
cout << " Power : " << Water << endl;
WeaponNature = Water;
break;
case 3:
cout << "You picked wind nature." << endl;
cout << " Power : " << Wind << endl;
WeaponNature = Wind;
break;
case 4:
cout << "You picked earth nature." << endl;
cout << " Power : " << Earth << endl;
WeaponNature = Earth;
break;
default:
cout << "Incorrect input. Your weapon will be : " << rand() // this is where i need help
}
}
When the default: runs in the switch() i wanted it to choose a random nature with rand(), please any help ): ?
As take from http://www.cprogramming.com/tutorial/enum.html:
Printing Enums
You might wonder what happens when you print out an enum: by default, you'll get the integer value of the enum. If you want to do something fancier than that, you'll have to handle it specially.
You would have to create another switch block converting the random integer into the proper value from the enum. Also, initialise a seed for your random number generator via srand( time( NULL ) )
Assign the rand value to WeaponNature as well.
This is a pretty specific question but my program seems to exiting its while loop before the condition is false. I added in quite a few memory checks for safety when I was debugging and it prints to screen that counter is 4 and SqRoot is 6 at the end which means it should still be looping through (TestNum=32). I definitely know it's getting past the loop with counter<=SqRoot because it prints both "The integer 32 is composite" and "The integer 32 is prime". Any help is very appreciated! Thanks so much
EDIT: I changed the overall logic of program and it is working now. Thanks!
#include <iostream>
#include <cmath>
using namespace std;
//Declare variables.
int TestNum, DivInt, SqRoot, PrintCounter(0), oppcounter;
float DivFloat, counter(2);
int main()
{
//Prompt user for input.
cout << "Input an positive integer to test its primality.";
cin >> TestNum;
//Check if input is positive.
while (TestNum < 0)
{
cout << "Please input a *positive* integer.";
cin >> TestNum;
}
//Square root.
SqRoot = sqrt(TestNum)+1;
//Loop to test if prime.
while (counter<=SqRoot)
{
++counter;
DivFloat = TestNum/counter;
DivInt = TestNum/counter;
oppcounter = TestNum/counter;
if (DivFloat-DivInt == 0)
{
++PrintCounter;
if (PrintCounter==1)
{
cout << "The integer " << TestNum << " is composite.\n " \
<< TestNum << " is divisible by\n";
};
cout << counter << " " << oppcounter;
cout << "counter* " << counter;
cout << " TestNum " << TestNum;
cout << " DivInt " << DivInt;
cout << " SqRoot " << SqRoot;
cout << " DivFloat " << DivFloat;
}
}
if (counter<=SqRoot)
{
cout << "The integer " << TestNum << " is prime.\n";
}
cout << "counter " << counter;
cout << " TestNum " << TestNum;
cout << " DivInt " << DivInt;
cout << " SqRoot " << SqRoot;
cout << " DivFloat " << DivFloat;
//End main.
return (0);
}
I am seeing the opposite behavior of what you are describing, and I can see why. It's possible that the code you have posted is different than the code you are executing.
As an aside, I added the line
cout << endl;
after the line
cout << " DivFloat " << DivFloat;
at couple of places to make the output more readable.
When I enter 32, I see the following output:
The integer 32 is composite.
32 is divisible by
4 8
counter* 4 TestNum 32 DivInt 8 SqRoot 6 DivFloat 8
counter 7 TestNum 32 DivInt 4 SqRoot 6 DivFloat 4.57143
When I enter 17, I see the following output:
counter 6 TestNum 17 DivInt 2 SqRoot 5 DivFloat 2.83333
The reasons for that:
You don't break out of the while loop when you have detected that a number is a composite.
As a result of that, you always break out of the while loop only when counter<=SqRoot evaluates to false. As a result, in the code below,
if (counter<=SqRoot)
{
cout << "The integer " << TestNum << " is prime.\n";
}
you never execute the line in the if block.
The program should behave correctly if you break out of the while loop when you detect a composite and change the logic in the last if block to:
if (counter > SqRoot)
{
cout << "The integer " << TestNum << " is prime.\n";
}
Why so strange check for prime?
for(int i = 2; i*i <= n; ++i)
{
if (n % i == 0)
{
cout << "not prime";
break;
}
}
So this program is supposed to collect weather temperatures over 7 days using a for loop and then basically just print them back out to the user with an average temperature and the highest recorded temperature. Keep in mind, the following piece of code is a part of a much larger program. Anyway, the problem seems to be the "highest_temp1" float variable. When I run the program it produces some sort of error code instead of the highest temperature. This piece of code was tested in a separate source file and it works no problem.
switch (choice)
{
case 3:
int n;
float temperatures [7];
float lastweektemp [7] = {12.56,8.65,7.5,10,7.9,5,8};
float highest_temp1, highest_temp2;
float accumulated_temp1, accumulated_temp2;
system("CLS");
cout << "____________Weather Data____________" << endl << endl;
for (n = 0; n<7; n++)
{
cout << "What is the temperature for Day " << n+1 << " ?" << endl;
cin >> temperatures[n];
if (highest_temp1 < temperatures [n])
{
highest_temp1 = temperatures [n];
}
if (highest_temp2 < lastweektemp [n])
{
highest_temp2 = lastweektemp [n];
}
accumulated_temp1 = accumulated_temp1 + temperatures[n];
accumulated_temp2 = accumulated_temp2 + lastweektemp [n];
}
cout << endl << " Day This Week Last Week" << endl;
for (n=0; n<7; n++)
{
cout << n+1 << temperatures[n] << lastweektemp[n] << endl;
}
system("CLS");
cout << " Weather Report" << endl;
cout << " --------------" << endl << endl;
cout << "Current Week: " << endl;
cout << "-------------" << endl;
for (n=0; n<7; n++)
{
cout << "Day " << n+1 << ": " << temperatures[n] << endl;
}
cout << endl << " Average: " << accumulated_temp1 / 7 << endl;
cout << " Highest Temperature: " << highest_temp1 << endl;
cout << "Last Week: " << endl;
cout << "----------" << endl;
for (n=0; n<7; n++)
{
cout << "Day " << n+1 << ": " << lastweektemp[n] << endl;
}
cout << endl << " Average: " << accumulated_temp2 / 7 << endl;
cout << " Highest Temperature: " << highest_temp2 << endl;
system("PAUSE");
}
The highest temperature in current week is 24 but it is printing "Highest Temperature: 3.45857e+032"
This exact 'error-code' is appearing every time I run the program it doesn't change.
I am a newbie hence why I can't upload a photo.
Any help would be appreciated. I'm doing a small assignment in college. This is my first question so go easy !!
You have not assigned any value to teh variable highest_temp1 and you are comparing it with another value.
Basically you will need to assign it a value first before you compare..
highest_temp1 = 10.00
(or anything that it is supposed to contain)
You have not initialised highest_temp1 (or highest_temp1 for that matter: after that I stopped looking).
Same for accumulated_temp, which gets not initialised. can be done via
float accumulated_temp1(0);
Initialize variables before using them
float highest_temp1(-FLT_MAX); // -FLT_MAX insures results of first compare
float highest_temp2(-FLT_MAX); // Could use -1.0/0.0 of -INFINITY instead
float accumulated_temp1(0.0);
float accumulated_temp2(0.0);
For float number condition use if statements switch is not able to work in case of float number, switch only work for integer number.