I am making a program, that can calculate a triangle if given some information but if I try to use "letters" or "," then, the program glitches and the program needs to be restarted. I am currently using double to hold the numbers and decimals but one of the rules with double is that you need to use "." for decimals, but i've hit the "," so much so I want to know if there is a way to fix it. I also want to know if the person can choose to write both numbers and letters in the same box.
#include <iostream>
#include <windows.h>
#include <math.h>
#define PI 3.14159265359
using namespace std;
void SetColor(int ForgC);
int failure = 0;
int wait;
double a, b, c, A, B, C = 90;
int main()
{
SetColor(10);
{
info:
while (GetAsyncKeyState(VK_RETURN))
{
}
system("cls");
cout << "\n\t\t\t\tFind triangle info\n" << endl;
SetColor(11);
cout << "\t\t\t\tNote: Use 0 if you don't have the number!" << endl;
SetColor(10);
cout << "What information do you have?";
SetColor(11);
cout << "\tIf you use decimal numbers then use \".\" not \",\"!";
SetColor(10);
cout << "a = ";
cin >> a;
cout << "b = ";
cin >> b;
cout << "c = ";
cin >> c;
cout << "A = ";
cin >> A;
cout << "B = ";
cin >> B;
while (GetAsyncKeyState(VK_RETURN))
{
}
}
{
calculate:
if (a == 0 && b == 0 && c == 0 && A == 0 && B == 0)
{
cout << "There need to be at least two numbers!\n" << endl;
system("pause");
failure = 1;
} // Failsafe
else if (c != 0)
{
if (a >= c || b >= c)
{
cout << "a or b cannot be greater than c!\n" << endl;
system("pause");
failure = 1;
}
} // Failsafe 2
else if (A >= 90 || B >= 90)
{
cout << "A or B cannot be equal to, or greater than 90!\n" << endl;
system("pause");
failure = 1;
;
} // Failsafe 3
if (a != 0 && c != 0)
{
b = sqrt(c * c - a * a);
A = asin(a / c) * 180 / PI;
B = 90 - A;
}
else if (b != 0 && c != 0)
{
a = sqrt(c * c - b * b);
A = acos(b / c) * 180 / PI;
B = 90 - A;
}
else if (a != 0 && b != 0)
{
c = sqrt(a * a + b * b);
A = atan(a / b) * 180 / PI;
B = 90 - A;
}
else if (c != 0 && A != 0)
{
a = c * sin(A);
b = c * cos(A);
B = 90 - A;
}
else if (c != 0 && B != 0)
{
A = 90 - B;
a = c * sin(A);
b = c * cos(A);
}
else if (a != 0 && B != 0)
{
b = a * tan(B);
c = sqrt(a * a + b * b);
A = 90 - B;
}
else if (b != 0 && A != 0)
{
a = b * tan(A);
c = sqrt(a * a + b * b);
B = 90 - A;
}
else if (a != 0 && A != 0)
{
b = a / tan(A);
c = sqrt(a * a + b * b);
B = 90 - A;
}
else if (b != 0 && B != 0)
{
a = b / tan(B);
c = sqrt(a * a + b * b);
A = 90 - B;
}
if (failure == 1)
{
goto failsafe;
}
goto answer;
}
{
failsafe:
failure = 0;
system("cls");
cout << "\n\t\t\t\tFind triangle info\n" << endl;
SetColor(11);
cout << "\t\t\t\tNote: Use 0 if you don't have the number!" << endl;
SetColor(10);
cout << "What information do you have?";
SetColor(11);
cout << "\tIf you use decimal numbers then use \".\" not \",\"!";
SetColor(10);
cout << "a = ";
cin >> a;
cout << "b = ";
cin >> b;
cout << "c = ";
cin >> c;
cout << "A = ";
cin >> A;
cout << "B = ";
cin >> B;
while (GetAsyncKeyState(VK_RETURN))
{
}
goto calculate;
}
answer:
while (1)
{
system("cls");
wait = 1;
cout << "\n\t\t\t\tFind triangle info\n" << endl;
SetColor(11);
cout << "\t\t\t\tNote: Use 0 if you don't have the number!" << endl;
SetColor(10);
cout << "What information do you have?";
SetColor(11);
cout << "\tIf you use decimal numbers then use \".\" not \",\"!";
SetColor(10);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;
cout << "A = " << A << endl;
cout << "B = " << B << endl;
cout << "C = " << C << endl;
cout << "\nDo you want to write new information? (";
SetColor(9);
cout << "Y";
SetColor(10);
cout << "/N)";
while (wait == 1)
{
if (GetAsyncKeyState(VK_RIGHT))
{
wait = 0;
}
else if (GetAsyncKeyState(VK_RETURN))
{
goto info;
}
}
system("cls");
wait = 1;
cout << "\n\t\t\t\tFind triangle info\n" << endl;
SetColor(11);
cout << "\t\t\t\tNote: Use 0 if you don't have the number!" << endl;
SetColor(10);
cout << "What information do you have?";
SetColor(11);
cout << "\tIf you use decimal numbers then use \".\" not \",\"!";
SetColor(10);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;
cout << "A = " << A << endl;
cout << "B = " << B << endl;
cout << "C = " << C << endl;
cout << "\nDo you want to write new information? (Y/";
SetColor(9);
cout << "N";
SetColor(10);
cout << ")";
while (wait == 1)
{
if (GetAsyncKeyState(VK_LEFT))
{
wait = 0;
}
else if (GetAsyncKeyState(VK_RETURN))
{
return 0;
}
}
}
}
void SetColor(int ForgC)
{
WORD wColor;
// We will need this handle to get the current background attribute
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
// We use csbi for the wAttributes word.
if (GetConsoleScreenBufferInfo(hStdOut, &csbi))
{
// Mask out all but the background attribute, and add in the forgournd color
wColor = (csbi.wAttributes & 0xF0) + (ForgC & 0x0F);
SetConsoleTextAttribute(hStdOut, wColor);
}
return;
}
You need to add error handling.
If input fails, you need to decide what to do. E.g. you can print an error message, clear the stream state and start over:
std::cin.exceptions(std::ios::failbit);
try
{
std::cout << "a = ";
std::cin >> a;
std::cout << "b = ";
std::cin >> b;
std::cout << "c = ";
std::cin >> c;
std::cout << "A = ";
std::cin >> A;
std::cout << "B = ";
std::cin >> B;
} catch(std::exception const& e)
{
std::cerr << "Error in input.\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max());
goto info;
}
May I heartily suggest not using goto for program flow (use loops). And you may also use non-exception error checking:
std::cout << "a b c A B = ";
if (!(std::cin >> a >> b >> c >> A >> B))
{
if (std::cin.eof())
{
std::cerr << "Goodbye\n";
exit(1);
}
std::cerr << "Error in input.\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max());
goto info;
}
PS. For the numeric_limits traits, include
#include <limits>
Apart from the usual tricky error handling with text input, in particular on the console, and the funny gotos: In order to change number formats (and others as well) you probably need to "imbue a locale" on cin (and, for consistency, on cout). I have never done it but this site has examples which look reasonable and simple: http://www.linuxtopia.org/online_books/programming_books/c++_practical_programming/c++_practical_programming_101.html
Related
I am trying to create a user-define function in C++ to prevent an endless loop from inputting an incorrect input for a double variable and check if an input is negative or zero. If that's the case the function will go into a do-while loop to ask the user to try again until the value is no longer something other than a double, negative, or zero.
The function fix() is the the user-defined
#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
using namespace std;
string fix(double x)
{
string B_error = "B cannot be zero or negative. Please try again: ";
string H_error = "H cannot be zero or negative. Please try again: ";
string h_error = "b cannot be zero or negative. Please try again: ";
string b_error = "h cannot be zero or negative. Please try again: ";
string r_error = "r cannot be zero or negative. Please try again: ";
string y_error;
while (!(cin >> x))
{
if (cin.fail())
{
cout << "Erroneous input. Please try again:\n";
cin.clear(); // used to prevent an endless loop if an input type is not an integer
cin.ignore(10000, '\n');
}
}
if (x == 'B')
{
y_error = B_error;
if (x <= 0)
{
do
{
return y_error;
cin >> x;
}
while (x <= 0);
}
}
return 0;
}
int main()
{
int selection;
double I, B, H, b, h, r, fix(double);
cout << "Please select the type of beam:\n"
<< "1) I-Beam\n"
<< "2) Rectangular Beam\n"
<< "3) Cylindrical Beam\n";
while (!(cin >> selection) || selection < 1 || selection > 3)
{
if (cin.fail() || selection < 1 || selection > 3)
{
cout << "Erroneous input. Please try again:\n";
cin.clear(); // used to prevent an endless loop if an input type is not an integer
cin.ignore(10000, '\n');
}
}
switch (selection)
{
case 1:
cout << "You have selected I-beam. All inputs must be in inches.\n"
<< "Please input the value for B: ";
fix(B);
cout << "Please input the value for H: ";
fix(H);
if (H <= 0)
{
do
{
cout << "H cannot be zero or negative. Please try again: ";
cin >> H;
}
while (H <= 0);
}
cout << "Please input the value for b: ";
fix(b);
if (b <= 0)
{
do
{
cout << "b cannot be zero or negative. Please try again: ";
cin >> b;
}
while (b <= 0);
}
else if (b > B)
{
do
{
cout << "b cannot be larger than B. Please try again: ";
cin >> b;
}
while (b > B);
}
cout << "Please input the value for h: ";
fix(h);
if (h <= 0)
{
do
{
cout << "h cannot be zero or negative. Please try again: ";
cin >> h;
}
while (h <= 0);
}
else if (h > H)
{
do
{
cout << "h cannot be larger than H. Please try again: ";
cin >> H;
}
while (h > H);
}
I = (B*H*H*H - b*h*h*h)/12.;
cout << "\nResults for an I-beam with B = " << B
<< ", H = " << H << ", b = " << b << ", and h = " << h << endl;
cout << setfill('-') << setw(32) << "" << endl;
break;
case 2:
cout << "You have selected rectangular beam. All inputs must be in inches.\n"
<< "Please input the value for b: ";
fix(b);
if (b <= 0)
{
do
{
cout << "b cannot be zero or negative. Please try again: ";
cin >> b;
}
while (b <= 0);
}
cout << "Please input the value for h: ";
fix(h);
if (h <= 0)
{
do
{
cout << "h cannot be zero or negative. Please try again: ";
cin >> h;
}
while (h <= 0);
}
I = b*h*h*h/12.;
cout << "\nResults for a rectangular beam with b = " << b << " and h = " << h << endl;
cout << setfill('-') << setw(32) << "" << endl;
break;
case 3:
cout << "You have selected cylindrical beam. All inputs must be in inches.\n"
<< "Please input the value of r: ";
fix(r);
if (r <= 0)
{
do
{
cout << "r cannot be zero or negative. Please try again: ";
cin >> r;
}
while (r <= 0);
}
I = M_PI*pow(r,4)/4.;
cout << "\nResults for a cylindrical beam with r = " << r << endl;
cout << setfill('-') << setw(32) << "" << endl;
break;
}
cout << "The value of the moment of inertia for this beam is: " << I << "in^4" << "\n\n";
return 0;
}
I removed the issues. You are confusing instances of classes with functions. Functions don't have to be initialized, instances have to if they are outside of the class.
I wrote some comments along the code. It is still not beautiful but at least it works.
string FUNCTION(double) btw. means the function only can or should return a "string". If you are returning nothing the function is written like so void FUNCTION(double).
If your return f.e. a string you have to write something that is receiving the returned string like so:
#include <iostream>
/*
std::string returning_value;
returning_value = FUNCTION(1.0);
*/
//or
std::string FUNCTION(double function_a); //prototype of the function
//you need this if you write the function underneath the main() function
//The main function is returning "return 0" so since "0" is an "int"
//meaning main is always "int main()" btw. because it is a function,
//just not some function but the "main function" thats called by the OS
int main()
{
std::string returning_value;
double a = 0.1; //initializing with 0.1
returning_value = FUNCTION(a);
std::cout << returning_value << std::endl;
//and in both cases the function would look like:
return 0;
}
std::string FUNCTION(double function_a)
{
std::string returning_value_a = "This is a string that will be returned";
if(function_a == 0.1)
{
returning_value_a = "This is another string";
}
return returning_value_a;
}
Your code with the least amount fixed that you got it at least working
and you can test with how to get the right output you want to get. Have fun :) Hope my answer helps you :)
#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
using namespace std;
void fix(double x)
{
string B_error = "B cannot be zero or negative. Please try again: ";
string H_error = "H cannot be zero or negative. Please try again: ";
string h_error = "b cannot be zero or negative. Please try again: ";
string b_error = "h cannot be zero or negative. Please try again: ";
string r_error = "r cannot be zero or negative. Please try again: ";
string y_error;
while (!(cin >> x))
{
if (cin.fail())
{
cout << "Erroneous input. Please try again:\n";
cin.clear(); // used to prevent an endless loop if an input type is not an integer
cin.ignore(10000, '\n');
}
}
//warning: comparing floating point with == or != is unsafe
if (x == 'B')
{
y_error = B_error;
if (x <= 0)
{
do
{
cin >> x;
}
while (x <= 0);
}
}
}
int main()
{
int selection;
double I, B, H, b, h, r;
//You need to initialize the variables with a value
I = 1.0;
B = 1.0;
H = 1.0;
b = 1.0;
h = 1.0;
r = 1.0;
//functions don't need to be initialized, thats for Instanzes of classes
//double fix(double);
cout << "Please select the type of beam:\n"
<< "1) I-Beam\n"
<< "2) Rectangular Beam\n"
<< "3) Cylindrical Beam\n";
while (!(cin >> selection) || selection < 1 || selection > 3)
{
if (cin.fail() || selection < 1 || selection > 3)
{
cout << "Erroneous input. Please try again:\n";
cin.clear(); // used to prevent an endless loop if an input type is not an integer
cin.ignore(10000, '\n');
}
}
switch (selection)
{
case 1:
cout << "You have selected I-beam. All inputs must be in inches.\n"
<< "Please input the value for B: ";
fix(B);
cout << "Please input the value for H: ";
fix(H);
if (H <= 0)
{
do
{
cout << "H cannot be zero or negative. Please try again: ";
cin >> H;
}
while (H <= 0);
}
cout << "Please input the value for b: ";
fix(b);
if (b <= 0)
{
do
{
cout << "b cannot be zero or negative. Please try again: ";
cin >> b;
}
while (b <= 0);
}
else if (b > B)
{
do
{
cout << "b cannot be larger than B. Please try again: ";
cin >> b;
}
while (b > B);
}
cout << "Please input the value for h: ";
fix(h);
if (h <= 0)
{
do
{
cout << "h cannot be zero or negative. Please try again: ";
cin >> h;
}
while (h <= 0);
}
else if (h > H)
{
do
{
cout << "h cannot be larger than H. Please try again: ";
cin >> H;
}
while (h > H);
}
I = (B*H*H*H - b*h*h*h)/12.;
cout << "\nResults for an I-beam with B = " << B
<< ", H = " << H << ", b = " << b << ", and h = " << h << endl;
cout << setfill('-') << setw(32) << "" << endl;
break;
case 2:
cout << "You have selected rectangular beam. All inputs must be in inches.\n"
<< "Please input the value for b: ";
fix(b);
if (b <= 0)
{
do
{
cout << "b cannot be zero or negative. Please try again: ";
cin >> b;
}
while (b <= 0);
}
cout << "Please input the value for h: ";
fix(h);
if (h <= 0)
{
do
{
cout << "h cannot be zero or negative. Please try again: ";
cin >> h;
}
while (h <= 0);
}
I = b*h*h*h/12.;
cout << "\nResults for a rectangular beam with b = " << b << " and h = " << h << endl;
cout << setfill('-') << setw(32) << "" << endl;
break;
case 3:
cout << "You have selected cylindrical beam. All inputs must be in inches.\n"
<< "Please input the value of r: ";
fix(r);
if (r <= 0)
{
do
{
cout << "r cannot be zero or negative. Please try again: ";
cin >> r;
}
while (r <= 0);
}
I = M_PI*pow(r,4)/4.;
cout << "\nResults for a cylindrical beam with r = " << r << endl;
cout << setfill('-') << setw(32) << "" << endl;
break;
}
cout << "The value of the moment of inertia for this beam is: " << I << "in^4" << "\n\n";
return 0;
}
So, I had to add another function to check if B < b and H < h and add a do-while loop after the while loop in the fix function.
Here's my code with the fix:
#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
using namespace std;
void fix(double &x)
{
while (!(cin >> x))
{
if (cin.fail())
{
cout << "Erroneous input. Please try again:\n";
cin.clear(); // used to prevent an endless loop if an input type is not a double
cin.ignore(10000, '\n');
}
}
string return_x = "This cannot be zero or negative. Please try again: ";
while (x <= 0)
{
cout << return_x << endl;
cin >> x;
}
}
void fix2(double &x, double &y)
{
while (x < y)
{
cout << x << " cannot be less than " << y << endl;
fix(y);
}
}
int main()
{
int selection;
double I = 1.0;
double B = 1.0;
double H = 1.0;
double b = 1.0;
double h = 1.0;
double r = 1.0;
cout << "Please select the type of beam:\n"
<< "1) I-Beam\n"
<< "2) Rectangular Beam\n"
<< "3) Cylindrical Beam\n";
while (!(cin >> selection) || selection < 1 || selection > 3)
{
if (cin.fail() || selection < 1 || selection > 3)
{
cout << "Erroneous input. Please try again:\n";
cin.clear(); // used to prevent an endless loop if an input type is not an integer
cin.ignore(10000, '\n');
}
}
switch (selection)
{
case 1:
cout << "You have selected I-beam. All inputs must be in inches.\n"
<< "Please input the value for B: ";
fix(B);
cout << "Please input the value for H: ";
fix(H);
cout << "Please input the value for b: ";
fix(b);
fix2(B, b);
cout << "Please input the value for h: ";
fix(h);
fix2(H, h);
I = (B * H * H * H - b * h * h * h) / 12.;
cout << "\nResults for an I-beam with B = " << B << ", H = " << H
<< ", b = " << b << ", and h = " << h << endl;
cout << setfill('-') << setw(32) << "" << endl;
break;
case 2:
cout << "You have selected rectangular beam. All inputs must be in inches.\n"
<< "Please input the value for b: ";
fix(b);
cout << "Please input the value for h: ";
fix(h);
I = b * h * h * h / 12.;
cout << "\nResults for a rectangular beam with b = " << b
<< " and h = " << h << endl;
cout << setfill('-') << setw(32) << "" << endl;
break;
case 3:
cout << "You have selected cylindrical beam. All inputs must be in inches.\n"
<< "Please input the value of r: ";
fix(r);
I = M_PI * pow(r, 4) / 4.;
cout << "\nResults for a cylindrical beam with r = " << r << endl;
cout << setfill('-') << setw(32) << "" << endl;
break;
}
cout << "The value of the moment of inertia for this beam is: " << I
<< "in^4" << "\n\n";
return 0;
}
so i have this assignment that tells the user to input two numbers and lets him choose some basic operations(like a calculator) from a menu.
The goal of this exercise is to help us get more familiar with pointers/pointers to functions/dynamic allocation...The professor prefers that we use the "malloc" and "calloc" commands.
There is a part I'm stuck on, the part of displaying the history. It works for the first execution, but gives a debugging error as the code proceeds. Is there anyone who can help me solve the issue?
c++ code:
#include <iostream>
using namespace std;
//structure for the history array
struct Operation{
float result;
int choice;
};
float add(float, float);
float sub(float, float);
float mult(float, float);
float divi(float, float);
int main(){
//size1=for 1st history array, size2=for 2nd history array, t=to check if an operation was done at least once
int choice,size1=0,t=0,i,size2=0;
//pointer to func
int(*operation)(int, int);
float a, b,result;
//pointers set to NULL
Operation *history1 = NULL, *history1i = NULL, *history2 = NULL, *history2i = NULL;
cout << "Enter 2 numbers a & b: ";
cin >> a >> b;
cout << "What would you like to do?" << endl << "1=Addition" << endl << "2=Subtraction" << endl << "3=Division" << endl;
cout << "4=Multiplication" << endl << "5=Display History" << endl << "6=Exit" << endl;
do{
cin >> choice;
//initialize the size of 1st array if a choice is valid
if (choice < 5 && choice >0)
size1++;
//initialize 1st array
history1 = (Operation*)calloc(size1, sizeof(Operation));
if (history1 == NULL){
cout << "History allocation failed."<<endl;
exit(0);
}
//menu
switch (choice){
case 1: result = (add)(a, b);
cout << endl << "The addition of " << a << " & " << b << " gives: " << result << endl;
break;
case 2:result = (sub)(a, b);
cout << endl << "The subtraction of " << a << " & " << b << " gives: " << result << endl;
break;
case 3:if (b != 0){
result = (divi)(a, b);
cout << endl << "The division of " << a << " & " << b << " gives: " << result << endl;
}
else
cout << "Can't perform the divison.";
break;
case 4:result = (mult)(a, b);
cout << endl << "The multiplication of " << a << " & " << b << " gives: " << result << endl;
break;
//display history
case 5:if (t == 1){
cout << endl << "Your history is: " << endl;
for (history2i = history2,i=1; (history2i - history2) < size2; history2i++,i++){
cout << "\t"<<i<<"- " << a;
if (history2i->choice == 1)
cout << " + ";
else if (history2i->choice == 2)
cout << " - ";
else if (history2i->choice == 3)
cout << " / ";
else
cout << " * ";
cout << b << " = " << history2i->result<<endl;
}
}
else
cout <<endl<< "You haven't done any calcualtions yet."<<endl;
break;
case 6:break;
default:cout << endl << "The option you entered is not valid." << endl;
break;
}
//if choice is valid
if (choice < 5 && choice >0){
//if at least one opertion executed copy the elements of history2 in history1
if (t == 1){
for (history1i = history1, history2i = history2; (history1i - history1) < size2; history1i++, history2i++){
history1i->result = history2i->result;
history1i->choice = history2i->choice;
}
history1i++;//in order to enter the new operation
}
//if no operation done
else{
history1i = history1;
}
history1i->result = result;
history1i->choice = choice;
}
//if at least one operation done=>history exists and not NULL
if (t == 1){
free(history2);//in order to create a new array with the new elements
history2 = NULL;
}
//if not operations done before increment t
if (choice < 5 && choice >0 && t == 0){
t++;
}
//if valid choice create history 2
if (choice < 5 && choice >0){
size2 = size1;
history2 = (Operation*)calloc(size2, sizeof(Operation));
if (history2 == NULL){
cout << "History allocation failed." << endl;
exit(0);
}
//store all the previous history including the new one
for (history2i = history2, history1i = history1; (history2i - history2) < size2; history2i++, history1i++){
history2i->result = history1i->result;
history2i->choice = history1i->choice;
}
}
free(history1);
history1 = NULL;
if (choice != 6)
cout << endl << "Choose another option: ";
} while (choice != 6);
return 0;
}
float add(float a, float b){
return a + b;
}
float sub(float a, float b){
return a - b;
}
float mult(float a, float b){
return a*b;
}
float divi(float a, float b){
return a / b;
}
I'm creating a text-based Risk game on C++. Been trying to implement the dice / battle function but it's been giving me the error "f is used without being initialized!" Which is weird because I initialized it earlier. Here's my code
void battle(int attack, int defend)
{
int a, b, c, d, e, f;
if (attack >= 3)
{
a = rollDice();
b = rollDice();
c = rollDice();
}
else if (attack == 2)
{
a = rollDice();
b = rollDice();
c = 0;
}
else if (attack == 1)
{
a = rollDice();
b = 0;
c = 0;
}
else if (defend >= 2)
{
d = rollDice();
e = rollDice();
f = 0;
}
else if (defend == 1)
{
d = rollDice();
e = 0;
f = 0;
}
sortValues(a, b, c);
sortValues(d, e, f);
cout << endl << "The attacking country rolled the following dices: " << a
<< " " << b << " " << c << ".";
cout << endl << "The defending country rolled the following dices: " << d
<< " " << e << " " << f << ".";
if (a == d)
{
attack = attack - 1;
}
else if (a != d)
{
if (a < d)
{
attack = attack - 1;
}
else if (a > d)
{
defend = defend - 1;
}
}
else if (b == e)
{
attack = attack - 1;
}
else if (b != e)
{
if (b < e)
{
attack = attack - 1;
}
else if (b > e)
{
defend = defend - 1;
}
}
// since the int f is never used, this function is critical to implement. so that we can avoid compile time error
_unused(f);
}
int main()
{
int attack;
int defend;
int choice;
// this asks for the user choice of what he would like to do.
cout << "How large is the attacking army?" << endl;
cin >> attack;
cout << "How large is the defending army?" << endl;
cin >> defend;
while (attack >= 1 && defend >= 1)
{
cout
<< "Based on the numbers you entered, you have a couple of choices: "
<< endl << endl;
cout << "1) Battle once" << endl;
cout << "2) Battle until the end" << endl;
cout << "3) Withdraw from the battle" << endl;
cout << "Please enter your game choice (just enter the number): "
<< endl;
cin >> choice;
if (choice == 1)
{
battle(attack, defend);
}
if (choice == 2)
{
do
{
battle(attack, defend);
} while (attack != 0 && defend != 0);
cout << "Battle ended. The attacking forces are: " << attack
<< " , while the defending forces are: " << defend << endl;
}
if (choice == 3)
{
break;
}
}
if (attack < 1)
{
cout
<< "The attacking forces have lost. Defending forces keep their territory"
<< endl;
}
else if (defend < 1)
{
cout << "The attacking forces have won over the territory." << endl;
}
system("pause");
return 0;
}
This isn't all of the code, but it's the critical section which includes and uses f.
In the battle function you are calling sortValues(d,e,f), but in the first 3 if-cases f does not get a value (thus is not initialized).
Actually you should get a similar error (is it really an error or a warning?) for d and in some of the cases you do not give a value to a,b and c.
Im sitting here for two hours and my mind is blowing. Im trying to code a generator for linear equation with one unknown. It has 3 combinations:
ax+b=c (ex. 2x-3=1)
a+bx=c (ex. 3-2x=1)
a+b=cx (ex. 4-6=2x)
So i did some simple math, made an algorithm (x=(c-b)/a), excluded zero from denominator etc. The whole point is that to make the result as integer. That's why there is this code:
while (((c - b) % (a) != 0))
{
do
{
a = rand() % 24 - 12;
} while (a == 0);
b = rand() % 24 - 12;
c = rand() % 24 - 12;
}
First two combinations are working perfectly, but third one isn't. The example of an output from the third one is:
5-7=6x AND the calculated solution is x = 2. It would be x=2 if there was a + between 5 and 7. And it always goes this way. This one digit is wrong. The problem situated not in printing in the console, but in calculations.
If you have any idea, please help me to solve this.
Here is the code:
#include <stdio.h>
#include <iostream>
#include <time.h>
#include <stdlib.h>
using namespace std;
int level_1()
{
/* LEVEL 1 - ROWNANIE Z 1 NIEWIADOMA*/
int a = 5, b = 123, c = 32;
double x;
double answer;
double licznik, mianownik;
cout << "level 1" << endl;
// losujemy kombinacje (1 z 3) dla roznorodnosci
int losowanie = 3;//= rand() % 3 + 1;
if (losowanie == 1) {
cout << "Rolled: 1" << endl << endl; // x jest przy wspolczynniku a
a = 5;
while (((c - b) % (a) != 0))
{
do
{
a = rand() % 24 - 12;
} while (a == 0);
b = rand() % 24 - 12;
c = rand() % 24 - 12;
}
if (a == 1) cout << "x";
else if (a == -1) cout << "-x";
else cout << a << "x";
if (b > 0) cout << "+" << b;
else if (b == 0) cout << "";
else cout << b;
cout << "=";
if (c >= 0) cout << c;
else cout << c;
x = (c - b) / a;
cout << endl << "Type x = ";
cin >> answer;
if (answer == x)
{
cout << endl << "good answer" << endl;
return 1;
}
cout << endl << "bad answer." << endl;
return 0;
}
else if (losowanie == 2){
cout << "Rolled: 2" << endl << endl; // x jest przy wspolczynniku b
a = 5;
while (((c - b) % (a) != 0))
{
do
{
a = rand() % 24 - 12;
} while (a == 0);
b = rand() % 24 - 12;
c = rand() % 24 - 12;
}
if (b!=0)
cout << b;
if (a < 0 || a == 0) cout << "";
else if (a>0) cout << "+";
if (a == 1) cout << "x";
else if (a == -1) cout << "-x";
else cout << a << "x";
cout << "=" << c;
x = (c - b) / a;
cout << endl << "Type x = ";
cin >> answer;
if (answer == x)
{
cout << endl << "good answer" << endl;
return 1;
}
cout << endl << "bad answer." << endl;
return 0;
}
else
{
cout << "You rolled: 3" << endl << endl; // x jest przy wspolczynniku c
a = 5;
while (((c - b) % (a) != 0))
{
do
{
a = rand() % 24 - 12;
} while (a == 0);
b = rand() % 24 - 12;
c = rand() % 24 - 12;
}
cout << a << endl << b << endl << c << endl;
if (c != 0) cout << c;
if (b != 0)
{
if (b > 0) cout << "+";
else cout << "";
cout << b;
}
cout << "=";
if (a == 1) cout << "x";
else if (a == -1) cout << "-x";
else cout << a << "x";
x = ((c - b) / a);
cout << endl<< "zzz" << x << endl;
cout << endl << "type x = ";
cin >> answer;
if (answer == x)
{
cout << endl << "good answer" << endl;
return 1;
}
cout << endl << "bad answer." << endl;
return 0;
}
return 1;
}
int main()
{
//cout << y << endl;
srand(time(NULL));
while (1){
level_1();
}
}
x=(c-b)/a only holds true for equations of the first form. The other ones would be x = (c-a)/b and x = (a+b)/c. You should change your while loops accordingly.
I'm solving some C++ problems from ebooks. I made this C++ program but it isn't working properly. I've 2 problems:
Even after applying the forumla (votePercentage = firstAnswer/totalVotes*100;) it isn't showing the output, but only 0.
The program should display the bar chart, how am I suppose to do that? Any hints, reference or solution will be appreciated.
Here is my code:
/*
* Write a program that provides the option of tallying up the
* results of a poll with 3 possible values.
* The first input to the program is the poll question;
* the next three inputs are the possible answers.
* The first answer is indicated by 1, the second by 2, the third by 3.
* The answers are tallied until a 0 is entered.
* The program should then show the results of the poll—try making
* a bar graph that shows the results properly scaled to fit on
* your screen no matter how many results were entered.
*/
#include <iostream>
#include <string>
void startPoll (void);
void showPoll (void);
void pollCheck (void);
std::string pollQuestion, answer1, answer2, answer3;
int pollChoice, firstAnswer, secondAnswer, thirdAnswer;
int main (void)
{
int totalVotes = 1;
float votePercentage;
startPoll();
showPoll();
for(;;totalVotes++)
{
if (pollChoice == 1)
{
firstAnswer = firstAnswer + 1;
}
else if (pollChoice == 2)
{
secondAnswer++;
}
else if (pollChoice == 3)
{
thirdAnswer++;
}
else
{
std::cout << "==============*======*======*==============\n"
<< " RESULT \n"
<< "==============*======*======*==============\n"
<< "Question: " << pollQuestion << "\n"
<< "Total Votes: " << totalVotes << "\n";
votePercentage = (firstAnswer/totalVotes)*100;
std::cout << answer1 << ": " << firstAnswer << " votes. | " << votePercentage << "\n";
votePercentage = secondAnswer/totalVotes*100;
std::cout << answer2 << ": " << secondAnswer << " votes. | " << votePercentage << "\n";
votePercentage = thirdAnswer/totalVotes*100;
std::cout << answer3 << ": " << thirdAnswer << " votes. | " << votePercentage << "\n";
return 0;
}
std::cout << "\nEnter your vote again\nOR\nuse 0 to show the results.\n";
std::cin >> pollChoice;
}
std::cout << "Error: Something went wrong!\n";
}
void startPoll (void)
{
std::cout << "Enter your poll question:\n";
getline (std::cin, pollQuestion, '\n');
std::cout << "Enter answer 1:\n";
getline (std::cin, answer1, '\n');
std::cout << "Enter answer 2:\n";
getline (std::cin, answer2, '\n');
std::cout << "Enter answer 3:\n";
getline (std::cin, answer3, '\n');
}
void showPoll (void)
{
std::cout << "==============|======|======|==============\n"
<< " POLL \n"
<< "==============|======|======|==============\n"
<< pollQuestion << "\n"
<< "1. " << answer1 << "\n"
<< "2. " << answer2 << "\n"
<< "3. " << answer3 << "\n\n"
<< "Enter 1,2 or 3:\n\n";
std::cin >> pollChoice;
pollCheck();
}
void pollCheck (void)
{
if (pollChoice != 1 && pollChoice != 2 && pollChoice != 3)
{
std::cout << "Wrong choice entered! Please try again.\n\n";
return showPoll();
}
}
You need to take care that integer/integer = integer. In your case, changing
(firstAnswer/totalVotes)*100
to
(1.0*firstAnswer/totalVotes)*100
or
(firstAnswer*100.0/totalVotes)
should work. They all give a floating point result.
Well, the solution for the Bar Chart could be the following:(Not written by me) I think thats very self explaining because its really basic
void line (int n, char c)
{
// this is the loop for n
for (int i = 0; i < n; i++)
cout << c << endl;
}
Here is my solution, you can see how I made the bars work by reading the comments.
#include <iostream>
using namespace std;
int main()
{
int a = 0;
int b = 0;
int c = 0;
cout << "What is your favorite animal? 1 Cat, ";
cout <<"2 Dog, 3 Fish, 0 Count votes" << endl;
//Choice counter
while (true)
{
int choice;
cout << "Choice: ";
cin >> choice;
if(choice == 1)
a++;
else if(choice == 2)
b++;
else if(choice == 3)
c++;
else if(choice == 0)
break;
else
continue;
}
cout << endl << " 1: " << a << endl;
cout << " 2: " << b << endl;
cout << " 3: " << c << endl;
cout << endl << "1\t" << "2\t" << "3\t" << endl;
//Finds the max voted option
int max = 0;
if(a > b && a > c)
max = a;
else if(b > c && b > a)
max = b;
else if(c > a && c > b)
max = c;
/* If the max voted option is bigger than 10, find by how much
we have to divide to scale the graph, also making 10 bar
units the max a bar can reach before scaling the others too */
int div =2;
if(max > 10)
{
do
{
max = max/div;
if(max < 10)
break;
div++;
}while(true);
}else
div = 1;
//Sets the final number for the bars
a=a/div;
b=b/div;
c=c/div;
if(a==0)
a++;
if(b==0)
b++;
if(c==0)
c++;
//Creates the bars
while(true)
{
if(a>0)
{
cout << "[]" << "\t";
a--;
}else
cout << " ";
if(b>0)
{
cout << "[]" << "\t";
b--;
}else
cout << " ";
if(c>0)
{
cout << "[]" << "\t";
c--;
}else
cout << " ";
cout << endl;
if(a==0 && b==0 && c==0)
break;
}
}