I tried to write Nested if condition statement to calculate salary Raise in three condition, such as full-time, 2 part-time, or temporary. However, the result of salary Raise cannot be calculated. Are there any logic problems here. don't know where the mistakes are. Please help. Thank you for your comment.
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
char employmentStatus;
float performanceScore, salaryRaise = 0.0;
double fullTimeSalary = 10000;
double partTimeSalary = 8000;
double tempSalary = 5000;
double rate;
double bonus =500;
cout << "What is your employment status?" << endl;
cout << "Enter 1 (full-time), 2 (part-time), or 3 (temporary)"<< endl;
cin >> employmentStatus;
cout << "Now enter your performance score" << endl;
cin >> performanceScore;
cout << endl;
cout << fixed << showpoint << setprecision(2);
if (employmentStatus == 1)
{
if(performanceScore >= 8)
{
rate = 0.04;
salaryRaise = fullTimeSalary * (1 + rate) + bonus;
}
else if (performanceScore < 8 && performanceScore >= 6)
{
rate = 0.025;
salaryRaise = fullTimeSalary * (1 + rate) + bonus;
}
else
{
salaryRaise = fullTimeSalary;
}
cout << "Your salary raise is: $" << salaryRaise << endl;
}
else if (employmentStatus == 2)
{
if (performanceScore >= 8)
{
rate = 0.03;
salaryRaise = partTimeSalary + (salaryRaise*rate);
}
if (performanceScore < 8 && performanceScore >= 6)
{
rate = 0.015;
salaryRaise = partTimeSalary + (salaryRaise*rate);
}
if (performanceScore < 6 )
{
salaryRaise = partTimeSalary
}
}
else if (employmentStatus == 3)
{
salaryRaise = tempSalary
}
else
{
cout << " No result" << endl;
}
cout << "Your salary raise is: $" << salaryRaise << endl;
system("pause");
return 0;
}
Your problems vary from logic to syntax.
Full code after my fix:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
char employmentStatus;
float performanceScore, salaryRaise = 0.0;
double fullTimeSalary = 10000;
double partTimeSalary = 8000;
double tempSalary = 5000;
double rate;
double bonus =500;
cout << "What is your employment status?" << endl;
cout << "Enter 1 (full-time), 2 (part-time), or 3 (temporary)"<< endl;
cin >> employmentStatus;
cout << "Now enter your performance score" << endl;
cin >> performanceScore;
cout << endl;
cout << fixed << showpoint << setprecision(2);
if (employmentStatus == '1')
{
if(performanceScore >= 8)
{
rate = 0.04;
salaryRaise = fullTimeSalary * (1 + rate) + bonus;
}
else if (performanceScore < 8 && performanceScore >= 6)
{
rate = 0.025;
salaryRaise = fullTimeSalary * (1 + rate) + bonus;
}
else
{
salaryRaise = fullTimeSalary;
}
cout << "Your salary raise is: $" << salaryRaise << endl;
}
else if (employmentStatus == '2')
{
if (performanceScore >= 8)
{
rate = 0.03;
salaryRaise = partTimeSalary + (salaryRaise*rate);
}
if (performanceScore < 8 && performanceScore >= 6)
{
rate = 0.015;
salaryRaise = partTimeSalary + (salaryRaise*rate);
}
if (performanceScore < 6 )
{
salaryRaise = partTimeSalary;
}
}
else if (employmentStatus == '3')
{
salaryRaise = tempSalary;
}
else
{
cout << " No result" << endl;
return 0;
}
cout << "Your salary raise is: $" << salaryRaise << endl;
return 0;
}
Problems detected and explained solutions:
Syntax: There are couple of semi colons missing, you should debug this yourself compiler tells you where exactly.
Logic: You were doing this if (employmentStatus == 1) instead of if (employmentStatus == '1'), this not a problem on syntax level since C++ does implicit conversion of char to its ASCII code please see my answer on this for better explanation.
Syntax: system("pause") look at this, this and this. Just drop it.
Logic: If there are no results you should quit don't go further and display the raise, hence you have to add return 0; in the last condition.
Related
I pressed 1 and entered information related to students. Then press 2 to get the calculations that fit the information I entered, but the trash values come out.
#include <iostream>
#include <cstring>
using namespace std;
struct Subject { //과목 정보
char Subname[30]; //과목이름
int Hakjum; //과목학점
char Grade[10]; //과목등급
float GPA; //과목평점
};
struct Student { //학생정보
char StdName[30]; //학생이름
int Hakbun; //학번
Subject Sub[3]; //과목
float AveGPA; //교과목 평균 평점
};
int main()
{
cout.precision(2);
cout << fixed;
int n = 0;
struct Student Stu[10]; //구조체변수 선언
while (n < 3) //반복문을 통해 1또는 2를 눌렀을 때 메뉴판으로 돌아오기
{
cout << "===== 메뉴 =====\n"; //메뉴판
cout << "1. 학생 성적 입력\n";
cout << "2. 전체 학생 성적 보기\n";
cout << "3. 프로그램 종료\n";
cout << "\n";
cout << "원하는 기능을 입력하세요 : ";
cin >> n;
if (n <= 1) { //1번 선택하였을 경우
for (int t = 0; t <= 1; t++)
{
cout << "*" << t + 1 << " 번째 학생 이름과 학번을 입력하세요.\n"; //이름과 학번을 입력 받음
cout << "이름 : ";
cin >> Stu[t].StdName;
cout << "학번 : ";
cin >> Stu[t].Hakbun;
cout << "\n";
cout << "\n";
cout << "* 수강한 과목3개와 각 교과목명, 과목학점, 과목등급을 입력하세요.\n"; //과목과, 학점, 등급을 입력받음
for (int a = 0; a < 3; a++)
{
cout << "교과목명 : ";
cin >> Stu[t].Sub[a].Subname;
cout << "과목학점수 : ";
cin >> Stu[t].Sub[a].Hakjum;
cout << "과목등급<A+ ~ F> : ";
cin >> Stu[t].Sub[a].Grade;
cout << "\n";
}
cout << "\n\n\n";
}
}
else if (n <= 2) { //2번 선택하였을 경우
cout << "\n\t\t전체 학생 성적 보기\n";
cout << "===================================================================\n";
for (int t = 0; t <= 1; t++) {
cout << "이름 : " << Stu[t].StdName << "\t학번 : " << Stu[t].Hakbun << "\n"; //학생의 개인정보 출력
cout << "===================================================================\n";
cout << "\t\t과목명 \t 과목학점 \t과목등급 \t과목평점\n";
cout << "===================================================================\n";
for (int a = 0; a < 3; a++) { //문자열 비교 연산자를 사용하여 등급을 평점으로 바꿈
if (Stu[t].Sub[a].Grade, "A+" == 0) {
Stu[t].Sub[a].GPA = 4.5 * Stu[t].Sub[a].Hakjum;
}
else if (Stu[t].Sub[a].Grade, "A0" == 0) {
Stu[t].Sub[a].GPA = 4.0 * Stu[t].Sub[a].Hakjum;
}
else if (Stu[t].Sub[a].Grade, "B+" == 0) {
Stu[t].Sub[a].GPA = 3.5 * Stu[t].Sub[a].Hakjum;
}
else if (Stu[t].Sub[a].Grade, "B0" == 0) {
Stu[t].Sub[a].GPA = 3.0 * Stu[t].Sub[a].Hakjum;
}
else if (Stu[t].Sub[a].Grade, "C+" == 0) {
Stu[t].Sub[a].GPA = 2.5 * Stu[t].Sub[a].Hakjum;
}
else if (Stu[t].Sub[a].Grade, "C0" == 0) {
Stu[t].Sub[a].GPA = 2.0 * Stu[t].Sub[a].Hakjum;
}
else if (Stu[t].Sub[a].Grade, "D+" == 0) {
Stu[t].Sub[a].GPA = 1.5 * Stu[t].Sub[a].Hakjum;
}
else if (Stu[t].Sub[a].Grade, "D0" == 0) {
Stu[t].Sub[a].GPA = 1.0 * Stu[t].Sub[a].Hakjum;
}
else if (Stu[t].Sub[a].Grade, "F" == 0) {
Stu[t].Sub[a].GPA = 0.0 * Stu[t].Sub[a].Hakjum;
}
Stu[t].AveGPA = (Stu[t].Sub[0].GPA + Stu[t].Sub[1].GPA + Stu[t].Sub[2].GPA) / (Stu[t].Sub[0].Hakjum + Stu[t].Sub[1].Hakjum + Stu[t].Sub[2].Hakjum); //평균 평점을 구함
cout << "\t\t" << Stu[t].Sub[a].Subname << "\t\t" << Stu[t].Sub[a].Hakjum << "\t " << Stu[t].Sub[a].Grade << "\t\t " << Stu[t].Sub[a].GPA << "\n"; //과목명, 과목학점, 과목등급, 과목평점 출력
}
cout << "===================================================================\n";
cout << "\t\t\t\t평균평점\t" << Stu[t].AveGPA << "\n\n";
}
}
}
return 0;
}
The output
enter image description here
I get a trash value in the "subject grade".
Expected
I want it to be calculated according to the number I enter.
I hope the "과목평점" is right.
This is garbage:
if (Stu[t].Sub[a].Grade, "A+" == 0) {
What it does is use comma operator. So first it will get Stu[t].Sub[a].Grade and... do nothing with it. Then it will get "A+" == 0, which is comparing string literal (const char* pointer) to 0, which is same as nullptr, which is false because string literal is not going to be nullptr. So this condition is always false. It's the last experssion with the comman operator, so this false result will be used for the if. Same for the rest of them.
It should be
if (std::strcmp(Stu[t].Sub[a].Grade, "A+") == 0) {
The function std::strcmp is declared in cstring header, which you already have included, and since you have using namespace std there, you can leave the std:: out if you feel confident you know std:: namespace functions well enough.
This question already has answers here:
Why do I get an infinite loop if I enter a letter rather than a number? [duplicate]
(4 answers)
Closed 5 years ago.
I decided to try to make a little game. It's a simple survival game. Part of it has people try to survive as long as they can by choosing options. I've scaled down the game as much as possible from 1000 lines to this for the minimum case.
At one part of the game it asks, "You were visited by a gifting clown. On a scale of 0-10, how badly do you want a gift?"
If they answer 0-10, the loop works fine. If they answer with a character, like y or n, the loop basically forces the game to execute where it no longer asks players for input on any other choices.
A previous while loop works, one where it will continue so long as the player is alive. This clown while loop is nested inside of it. I have broken up the while loop with the clown section to where I think the problem is... And also included the full code just in case it's not inside there.
My goal is simply if a character is put into it, that it doesn't break this game.
main.cpp - clown section
encounterHurt = 0;
randomEncounter = rand() % 8;
cin.ignore(1, '\n');
if (randomEncounter == 1 && clown == true){
encounterChoice = 1;
cout << "\n\nYou were visited by a gifting clown. \nOn a scale of 0-10, how badly do you want a gift? ";
while (encounterChoice >= 0 && encounterChoice <= 10){
cin >> encounterChoice;
encounterFood = (rand() % 3) + encounterChoice / 2;
encounterWood = (rand() % 3) + encounterChoice / 2;
encounterMedicine = (rand() % 2);
encounterBullets = (rand() % 2);
if (encounterChoice > 0){
encounterHurt = (rand() % 10) - encounterChoice;
if (encounterHurt <= 1){
health--;
cout << "The crazy clown stabs you, but still provides gifts.";
}
}
if (encounterFood > 0) {
cout << "\nYou were provided with " << encounterFood << " food." << endl;
food += encounterFood;
}
if (encounterWood > 0) {
cout << "\nYou were provided with " << encounterWood << " wood." << endl;
wood += encounterWood;
}
if (encounterMedicine > 0) {
cout << "\nYou were provided with " << encounterMedicine << " medicine." << endl;
medicine += encounterMedicine;
}
if (encounterBullets > 0) {
cout << "\nYou were provided with " << encounterBullets << " bullets." << endl;
bullets += encounterBullets;
}
encounterChoice = 11;
}
main.cpp - Condensed code
#include <iostream>
#include <iomanip>
#include <random>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main() {
srand (time(NULL));
int randNumber = 0;
int food = 4;
int wood = 4;
int medicine = 2;
int bullets = 8;
int money = 25;
int randomEncounter = 0;
int hunt = 0;
bool axe = false;
int axeTemp = 0;
int axeBonus = 0;
int lumberTemp = 0;
int lumber = 0;
int findStore = 0;
int storeChoice = 0;
bool gun = false;
int gunSearch;
int gunTemp;
int gunBonus = 0;
int gunFind = 0;
// int searches;
// int searchesBonus;
int farmFind = 0;
int farmFood = 0;
int farmSearch = 0;
bool farm = false;
string description;
int foodTemp = 0;
int woodTemp = 0;
int medicineTemp = 0;
int bulletsTemp = 0;
int moneyTemp = 0;
int huntTemp = 0;
int huntSuccess = 0;
char huntChoice;
int encounterFood = 0;
int encounterWood = 0;
int encounterBullets = 0;
int encounterMedicine = 0;
int encounterHurt = 0;
unsigned int encounterChoice = 0;
int hurt = 0;
int health = 3;
int healthMax = 3;
int days = 1;
char action = '0';
char pause = '1';
char classChoice;
char mainChoice;
bool clown = true;
int clownHealth = 5;
char clownChoice;
int yourShot = 0;
int clownShot = 0;
string place;
//Food 1 per day per person. Can expand to include more people.
//Fuel 1 per day, takes that much to stay warm even if fewer people
//Medicine used one per wound
//Bullets 1 to hunt, though can spend more to increase chance of success.
//Days how many days that they have survied.
//Health, everyone starts with three health. Good, okay, bad, dead.
cout << "\nFood: " << food << " Wood: " << wood << " Medicine: " << medicine << " Bullets: " << bullets << " Health: " << health << endl;
while (health > 0){
cout << "\nDay: " << days;
cout << "\nFood: " << food
<< "\nWood: " << wood
<< "\nMedicine: " << medicine
<< "\nBullets: " << bullets
<< "\nHealth: " << health
<< "\nMoney: " << money << endl;
if (food >= 1){
food--;
}
if (wood >= 1){
wood--;
}
if (food <= 0){
health--;
cout << "Health lost due to lack of food" << endl;
}
if (health < healthMax && medicine > 0){
health++;
medicine--;
cout << "Health pack used to heal your character\nHealth : " << health << endl;
}
action = '0';
cout << "\n1: Find food" << endl;
cout << "What's your action? ";
cin >> action;
cout << endl;
if (action == '1'){
//
//Section for random sites to search.
//
//
randNumber = rand() % 4;
description = "";
//Maybe + days at the end, and subtract some, so that they eventually run out of places to check.
if (randNumber >= 0 && randNumber < 2) {
place = "supermarket";
foodTemp = (rand() % 4) + 1;
woodTemp = (rand() % 2) + 0;
bulletsTemp = (rand() % 2) + 0;
medicineTemp = (rand() % 2) + 1;
moneyTemp = (rand() % 5) + 5;
}
if (randNumber >= 2 && randNumber < 4) {
place = "boat house";
foodTemp = (rand() % 2) + 1;
woodTemp = (rand() % 4) + 1;
bulletsTemp = (rand() % 2) + 0;
medicineTemp = (rand() % 2) + 0;
moneyTemp = (rand() % 3) + 0;
}
cout << "You have come to the " << place << "." << endl;
cout << description << endl;
food += foodTemp;
wood += woodTemp;
bullets += bulletsTemp;
medicine += medicineTemp;
money += moneyTemp;
if (foodTemp > 0)
cout << "You have found " << foodTemp << " food." << endl;
if (woodTemp > 0)
cout << "You have found " << woodTemp << " wood." << endl;
if (medicineTemp > 0)
cout << "You have found " << medicineTemp << " medicine." << endl;
if (bulletsTemp > 0)
cout << "You have found " << bulletsTemp << " bullets." << endl;
if (moneyTemp > 0)
cout << "You have found " << moneyTemp << " money." << endl;
cout << "\nFood: " << food << " Wood: " << wood << " Medicine: " << medicine << " Bullets: " << bullets
<< " Health: " << health << " Money: " << money << endl;
//End of search rooms.
}
//Random encounter chance to see if they can gain additional items.
encounterHurt = 0;
randomEncounter = rand() % 8;
cin.ignore(1, '\n');
if (randomEncounter == 1 && clown == true){
encounterChoice = 1;
cout << "\n\nYou were visited by a gifting clown. \nOn a scale of 0-10, how badly do you want a gift? ";
while (encounterChoice >= 0 && encounterChoice <= 10){
cin >> encounterChoice;
encounterFood = (rand() % 3) + encounterChoice / 2;
encounterWood = (rand() % 3) + encounterChoice / 2;
encounterMedicine = (rand() % 2);
encounterBullets = (rand() % 2);
if (encounterChoice > 0){
encounterHurt = (rand() % 10) - encounterChoice;
if (encounterHurt <= 1){
health--;
cout << "The crazy clown stabs you, but still provides gifts.";
}
}
if (encounterFood > 0) {
cout << "\nYou were provided with " << encounterFood << " food." << endl;
food += encounterFood;
}
if (encounterWood > 0) {
cout << "\nYou were provided with " << encounterWood << " wood." << endl;
wood += encounterWood;
}
if (encounterMedicine > 0) {
cout << "\nYou were provided with " << encounterMedicine << " medicine." << endl;
medicine += encounterMedicine;
}
if (encounterBullets > 0) {
cout << "\nYou were provided with " << encounterBullets << " bullets." << endl;
bullets += encounterBullets;
}
encounterChoice = 11;
}
//Option to attack clown
//
//
}
//End of random encounter from the clown.
//Pause mechanic to prevent the game from cycling.
// pause = 'b';
// while (pause != 'a'){
// cout << "\nEnter a to continue: ";
// cin >> pause;
// }
//End of game message
cout << endl;
if (days == 100){
cout << "You have made it to 100 days. You have beaten this game. You can quit now, or try to see how long you'll last." << endl;
}
//Add day at end of while loop.
days++;
}
cout << "You have died after " << days << " days" << endl;
}
From another Stack Overflow question...
When an error occurs when reading from a stream, an error flag gets
set and no more reading is possible until you clear the error flags.
That's why you get an infinite loop.
cin.clear(); // clears the error flags
// this line discards all the input waiting in the stream
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
I am creating an RPG shop. It must have items, gold, and item price. Essentially creating an inventory. What i am trying to accomplish is, where the players gold is 0 they cannot add any more items to their inventory, and cannot have negative gold.
When running my code in debug mode it appears to be doing what i want, but when the function exits the amount the player requested has not been countered.
Keep in mind i am still new to c++.
Thanks
#include <iostream>
#include <string>
using namespace std;
// Global consts
const int numItems = 4;
const string items[numItems] = {"boots", "hats", "cats", "bats"}; // create string array of numItems items.
// Create stuct, that holds:
// Item, gold, price.
struct Inv {
int pInv[numItems] = {0, 0, 0, 0};
int gold = 100;
int itemPrice[numItems] = { 10, 6, 12, 15 };
}inv;
void iniItems();
void printItems();
bool buyItems();
bool sellItems();
int main() {
bool isDone = false;
iniItems();
while (isDone == false) {
printItems();
int choice;
bool x = false;
cout << "\nWhat would you like to do? Enter (" << 1 << "-" << 2 << "): " << endl;
cout << "1: Buy Items. \n2: Sell Items." << endl; cin >> choice; cout << endl;
while (x == false) {
if (choice == 1) {
x = buyItems();
}
if (choice == 2) {
x = sellItems();
}
}
}
system("pause");
// dynamic memory not implemented yet. Must wait for working fix of shoppe.cpp
}
void iniItems() {
cout << "** Shop Inventory: **" << endl;
for (int i = 0; i < numItems; i++) {
cout << i + 1 << " - " << items[i] << " - price: $" << inv.itemPrice[i] << endl;
}
}
void printItems() {
cout << "\n** Player Inventory: **" << endl;
cout << "Gold: $" << inv.gold << endl;
for (int i = 0; i < numItems; i++) {
cout << inv.pInv[i] << " x " << items[i] << endl;
}
}
bool buyItems() {
bool exit = false;
int amount;
const int remainder = 10;
printItems();
cout << "\nEnter -1 to quit." << endl;
cout << "What would you like to buy? Enter (" << 1 << "-" << 4 << "): " << endl;
// Get item info.
while (exit == false) {
int inp;
cout << "Item: "; cin >> inp; cout << endl;
cout << "Amount: "; cin >> amount; cout << endl;
// Check if input is valid.
if (inp > 0 && inp <= numItems) {
if (amount >= 0) {
inv.pInv[inp - 1] = 1 * amount;
inv.gold = inv.itemPrice[inp - 1] / amount;
}
// If gold is 0, make sure the user cannot gain more items.
if (inv.gold <= 0) {
int tmp;
inv.gold = 0;
tmp = remainder - amount;
for (int i = tmp; i >= 0; i++) {
inv.pInv[inp - 1]--;
}
return inv.pInv[inp - 1];
}
if (inp == -1) {
return true;
}
if (inp > numItems) {
cout << "Enter valid number." << endl;
return false;
}
else return false;
}
}
if (exit == true) {
return true;
}
}
So i limited the code down into a do while loop with a counter for the gold, in the buyItems() function.
Here it is, if anyone is interested.
do {
inv.gold -= inv.itemPrice[inp - 1];
++(inv.pInv[inp - 1]);
} while (inv.gold > 0);
if (inv.gold < 0) {
inv.gold = 0;
inv.pInv[inp - 1]--;
}
printItems();
This is what I've written so far. I thought it would work perfectly, seeing as I mostly transcribed it from my old Plinko lab code where I didn't use functions, changing it so that the simulator chunk became its own function. I get five errors, however.
In line 17 (ran = ran() % 2): "expression preceding parentheses of apparent call must have (pointer-to-) function type". What does this mean?
In line 10 ((srand(time(0));): "'argument': conversion from 'time_t' to 'unsigned int', possible loss of data". What does this mean?
In line 17 again: "term does not evaluate to a function taking 0 arguments". What does this mean?
In line 99 (drop_simulator(slot_number, 1);): "'argument': conversion from 'double' to 'int', possible loss of data". How do I prevent this?
In line 129 (total_rewards += drop_simulator(slot_number, 0);): same as above.
I would appreciate any help. I feel I've done everything I possibly can but feel as if I've run into a brick wall with this one.
#include <iostream>
#include <cstdlib>
#include <math.h>
#include <time.h>
using namespace std;
double drop_simulator(int slot_number, int number_of_chips_dropped)
{
srand(time(0));
double plink;
double ran;
double location;
location = slot_number;
for (int i = 0; i < 12; i++)
{
ran = (ran() % 2);
plink = ran;
plink -= 0.5;
location += plink;
if (location >= 8)
{
location -= 1;
}
else if (location <= 0)
{
location += 1;
}
if (number_of_chips_dropped == 1)
{
cout << location << endl;
}
}
int reward = 0;
if (location == 0)
{
reward = 100;
}
else if (location == 1)
{
reward = 500;
}
else if (location == 2)
{
reward = 1000;
}
else if (location == 3)
{
reward = 0;
}
else if (location == 4)
{
reward = 10000;
}
else if (location == 5)
{
reward = 0;
}
else if (location == 6)
{
reward = 1000;
}
else if (location == 7)
{
reward = 500;
}
else if (location == 8)
{
reward = 100;
}
return reward;
}
int main()
{
int input = 0;
while (input != 3)
{
cout << "Please select one of these three options." << endl;
cout << "1 - Drop a single chip into one slot" << endl;
cout << "2 - Drop multiple chips into one slot" << endl;
cout << "3 - Quit the program" << endl;
cin >> input;
cout << endl;
if (input == 1)
{
double slot_number;
cout << "Pick a slot (0 - 8) into which you'd like to drop your chip: ";
cin >> slot_number;
cout << endl;
if (slot_number < 0 || slot_number > 8)
{
cout << "INVALID SELECTION" << endl << endl;
}
else if (slot_number >= 0 && slot_number <= 8)
{
double reward = 0;
drop_simulator(slot_number, 1);
cout << "You won $" << reward << "!" << endl;
}
}
else if (input == 2)
{
int number_of_chips_dropped;
cout << "How many chips would you like to drop?" << endl;
cin >> number_of_chips_dropped;
cout << endl;
if (number_of_chips_dropped <= 0)
{
cout << "INVALID SELECTION. Please enter a positive number." << endl << endl;
}
else if (number_of_chips_dropped > 0)
{
double slot_number;
cout << "Pick a slot (0 - 8) into which you'd like to drop your chips.";
cin >> slot_number;
cout << endl;
if (slot_number < 0 || slot_number > 8)
{
cout << "INVALID SELECTION" << endl << endl;
}
else if (slot_number >= 0 && slot_number <= 8)
{
double total_rewards = 0;
for (int i = 0; i < number_of_chips_dropped; i++)
{
total_rewards += drop_simulator(slot_number, 0);
}
double average_winnings = total_rewards / number_of_chips_dropped;
cout << "The average rewards per chip was $" << average_winnings << "." << endl;
cout << "Your total rewards were $" << total_rewards << "." << endl;
}
}
}
else if (input < 1 || input > 3)
{
cout << "INVALID SELECTION. Please enter 1, 2 or 3." << endl << endl;
}
else if (input == 3)
{
cout << "GOODBYE" << endl << endl;
system("pause");
}
}
return 0;
}
The error messages really are trying to tell about the problem:
Line 17:
ran = (ran() % 2);
"expression preceding parentheses of apparent call must have (pointer-to-) function type".
Here ran() (the token before the parantheses) is flagged as not being a function or pointer-to-function type.
Similar
"term does not evaluate to a function taking 0 arguments"
indicates that ran()is not known to be a declared function in current scope.
Likely you intended to use rand() here to get a random number.
Line 10:
srand(time(0));
argument': "conversion from 'time_t' to 'unsigned int', possible loss of data"
srandis takig an unsigned intas parameter type. You are pasing the return value of time(0) to it. This is a time_t. (Likely a kind of long.) This could loose some bits of precision (longto int). As you likely would not care for initialyzing the RNG, you could use an explicit cast:
srand((unsigned int)time(0));
Line 99:
drop_simulator(slot_number, 1);
and
Line 129:
total_rewards += drop_simulator(slot_number, 0);
causing
"'argument': conversion from 'double' to 'int', possible loss of data"
suffer from slot_number being defined as double with mainwhile the formal parameter to drop_simulatoris being declared asìnt. As double can represent more values that int, you get the problem indicated. For fixing this you could just change the declaration ofslot_number`to:
int slot_number;
in main.
In line 17 (ran = ran() % 2): "expression preceding parentheses of apparent call must have (pointer-to-) function type". What does this mean?
This is because ran is not a function name, you perhaps intended
ran = rand() % 2
which makes ran be the result of a call to function rand modulo'd by 2.
This will fix your second error on line 17.
In line 99 (drop_simulator(slot_number, 1);): "'argument': conversion from 'double' to 'int', possible loss of data". How do I prevent this?
In line 129 (total_rewards += drop_simulator(slot_number, 0);): same as above.
This is because you've needlessly declared "slot_number" as a double. This means a user could enter a value such as "1.2345" which you don't want. Simply change your declarations of slot_number from double slot_number to int slot_number.
In line 10 ((srand(time(0));): "'argument': conversion from 'time_t' to 'unsigned int', possible loss of data". What does this mean?
It means that srand expects an unsigned integer but time(0) returns a time_t. You can fix this with casting:
srand(unsigned int(time(0)));
Full code:
#include <iostream>
#include <cstdlib>
#include <math.h>
#include <time.h>
using namespace std;
double drop_simulator(int slot_number, int number_of_chips_dropped)
{
srand(static_cast<unsigned int>(time(0)));
double plink;
double ran;
double location;
location = slot_number;
for (int i = 0; i < 12; i++)
{
ran = (rand() % 2);
plink = ran;
plink -= 0.5;
location += plink;
if (location >= 8)
{
location -= 1;
}
else if (location <= 0)
{
location += 1;
}
if (number_of_chips_dropped == 1)
{
cout << location << endl;
}
}
int reward = 0;
if (location == 0)
{
reward = 100;
}
else if (location == 1)
{
reward = 500;
}
else if (location == 2)
{
reward = 1000;
}
else if (location == 3)
{
reward = 0;
}
else if (location == 4)
{
reward = 10000;
}
else if (location == 5)
{
reward = 0;
}
else if (location == 6)
{
reward = 1000;
}
else if (location == 7)
{
reward = 500;
}
else if (location == 8)
{
reward = 100;
}
return reward;
}
int main()
{
int input = 0;
while (input != 3)
{
cout << "Please select one of these three options." << endl;
cout << "1 - Drop a single chip into one slot" << endl;
cout << "2 - Drop multiple chips into one slot" << endl;
cout << "3 - Quit the program" << endl;
cin >> input;
cout << endl;
if (input == 1)
{
int slot_number;
cout << "Pick a slot (0 - 8) into which you'd like to drop your chip: ";
cin >> slot_number;
cout << endl;
if (slot_number < 0 || slot_number > 8)
{
cout << "INVALID SELECTION" << endl << endl;
}
else if (slot_number >= 0 && slot_number <= 8)
{
double reward = 0;
drop_simulator(slot_number, 1);
cout << "You won $" << reward << "!" << endl;
}
}
else if (input == 2)
{
int number_of_chips_dropped;
cout << "How many chips would you like to drop?" << endl;
cin >> number_of_chips_dropped;
cout << endl;
if (number_of_chips_dropped <= 0)
{
cout << "INVALID SELECTION. Please enter a positive number." << endl << endl;
}
else if (number_of_chips_dropped > 0)
{
int slot_number;
cout << "Pick a slot (0 - 8) into which you'd like to drop your chips.";
cin >> slot_number;
cout << endl;
if (slot_number < 0 || slot_number > 8)
{
cout << "INVALID SELECTION" << endl << endl;
}
else if (slot_number >= 0 && slot_number <= 8)
{
double total_rewards = 0;
for (int i = 0; i < number_of_chips_dropped; i++)
{
total_rewards += drop_simulator(slot_number, 0);
}
double average_winnings = total_rewards / number_of_chips_dropped;
cout << "The average rewards per chip was $" << average_winnings << "." << endl;
cout << "Your total rewards were $" << total_rewards << "." << endl;
}
}
}
else if (input < 1 || input > 3)
{
cout << "INVALID SELECTION. Please enter 1, 2 or 3." << endl << endl;
}
else if (input == 3)
{
cout << "GOODBYE" << endl << endl;
system("pause");
}
}
return 0;
}
live demo: http://ideone.com/dp7sLN
This program should be accepting a bet, generating a set of cards for each player, and adding the bet to the winner's pool. This is a class project. I cannot figure out what the problem is on line 60.
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
struct cards {
int value;
string face;
string suit;
bool facebool;
};
struct hand {
cards card[4];
int antiduplicate[52];
};
struct player {
string name;
int sum;
int money;
hand hand;
int bet;
};
struct points {
int player1;
int player2;
};
hand drawhand(int [52]);
points calcvalue(player, player);
int winner(player, player);
int main() {
points store = {};
player house = {"The House"};
player player1 = {};
srand (time(0));
cout << "Enter player 1's name:";
getline(cin,player1.name);
cout << "Enter player 1's money:";
cin >> player1.money;
cout << endl;
house.money = (player1.money + 1);
do{
int deckarray[52] = {0};
//do{
cout << "What do you want to bet?\n";
/* line 60 */ cin >> player1.bet;
cout << "check";
if (player1.bet < player1.money){
}
else if (player1.bet > player1.money){
cout << "\nYou cannot go into debt!!\n";
}
else if (player1.bet == 0){
cout << "\nYou ended the game!";
return 0;
}
//}while (bet > player1.money);
house.hand = drawhand(deckarray);
for (int i = 0; i < 52; i++) {
if (house.hand.antiduplicate[i] == 1)
deckarray[i] = 1;
}
player1.hand = drawhand(deckarray);
for (int i = 0; i < 52; i++) {
if (player1.hand.antiduplicate[i] == 1)
deckarray[i] = 1;
}
cout << "\nCheck check\n";
store = calcvalue(player1, house);
player1.sum = store.player1;
house.sum = store.player2;
cout << player1.name << "'s hand:\n" << player1.hand.card[1].face << " of " <<player1.hand.card[1].suit << endl
<< player1.hand.card[2].face << " of " <<player1.hand.card[2].suit << endl <<player1.hand.card[3].face << " of " <<player1.hand.card[3].suit << endl;
cout << ">> " <<player1.name << " scored " << player1.sum << " points!\n\n";
cout << house.name << "'s hand:\n" << house.hand.card[1].face << " of " <<house.hand.card[1].suit << endl
<< house.hand.card[2].face << " of " <<house.hand.card[2].suit << endl <<house.hand.card[3].face << " of " <<house.hand.card[3].suit << endl;
cout << ">> " << house.name << " scored " << house.sum << " points!\n";
int win;
win = winner(player1, house);
if (win == 1){
cout << "\n" << player1.name << " wins the round!!" << endl;
player1.money = (player1.money + player1.bet); house.money = (house.money - player1.bet);
}
else if (win == -1){
cout << "\n\n" << house.name << " wins the round!!";
house.money = (house.money + player1.bet);
player1.money = (player1.money - player1.bet);
}
else if (win == 0){
cout << "\n\n" << house.name << " wins the round!!";
house.money = (house.money + player1.bet);
player1.money = (player1.money - player1.bet);
}
cout << endl << "House money: " << house.money << endl << "Player money: " << player1.money << endl << endl;
}while (player1.money > 0 && house.money > 0 && player1.bet != 0);
cout << "Game over!";
return 0;
}
hand drawhand(int deckarray[52])
{
string tsuit, tface;
int tvalue;
int suitvalue, facevalue;
bool tfacebool;
hand thand;
for (int i = 0; i < 4; i++) {
for (int i = 0; i < 52; i++) {
if (deckarray[i] == 1)
thand.antiduplicate[i] = 1;
}
int index;
do {
index = rand()%52;
} while (thand.antiduplicate[i] == 1);
thand.antiduplicate[i] = 1;
facevalue = (index%13 + 1);
suitvalue = (index / 13);
switch (suitvalue)
{
case 0: tsuit = "Hearts";
break;
case 1: tsuit = "Diamonds";
break;
case 2: tsuit = "Clubs";
break;
case 3: tsuit = "Spades";
break;
}
switch (facevalue)
{
case 1: tface = "Ace";
tvalue = 1;
break;
case 11: tface = "Jack";
tvalue = 10;
tfacebool = true;
break;
case 12: tface = "Queen";
tvalue = 10;
tfacebool = true;
break;
case 13: tface = "King";
tvalue = 10;
tfacebool = true;
break;
}
if ((facevalue > 1) && (facevalue < 11))
tface = to_string(facevalue);
if (facevalue < 11) tvalue = facevalue;
thand.card[i].suit = tsuit;
thand.card[i].face = tface;
thand.card[i].value = tvalue;
thand.card[i].facebool = tfacebool;
}
return thand;
}
points calcvalue(player player1, player house)
{
points tpoints;
player1.sum = ((player1.hand.card[1].value + player1.hand.card[2].value + player1.hand.card[3].value) % 10);
if (player1.hand.card[1].facebool == true && player1.hand.card[2].facebool == true && player1.hand.card[3].facebool == true)
player1.sum = 10;
house.sum = ((house.hand.card[1].value + house.hand.card[2].value + house.hand.card[3].value) % 10);
if (house.hand.card[1].facebool == true && house.hand.card[2].facebool == true && house.hand.card[3].facebool == true)
house.sum = 10;
tpoints.player1 = player1.sum;
tpoints.player2 = house.sum;
return tpoints;
}
int winner(player player1, player house){
int winorlose;
if (player1.sum > house.sum)
{winorlose = 1;}
else if (player1.sum < house.sum)
{winorlose = -1;;}
else if (player1.sum == house.sum)
{winorlose = 0;}
return winorlose;
}
I see a lot of problems at first glance actually. eg: You've called a hand object 'hand' (thus redefining it), if you're going to call your object names the same as their class/struct, at least differentiate them with capitalization. eg: call your hand struct "Hand" instead of "hand"
cout << "What do you want to bet? ";
cin >> player1.bet; // <==== problem
cout << "check";
if (player1.bet < player1.money){
}
else if (player1.bet > player1.money){
cout << "\nYou cannot go into debt!!\n";
}
else if (player1.bet == 0){
cout << "\nYou ended the game!";
return 0;
}
That being said the issue you are having specifically relating to this section of code probably has something to do with a "\n" staying in the buffer and not getting cleared. Try using cin.ignore(numeric_limits::max(),'\n'); to solve this problem (don't forget to #include limits as well).
Similar problem here: c++ cin input not working?
Unfortunately I'm pressed for time and don't have time for a thorough look. :(