c++ Division . seemingly simple thing driving me crazy, advice please - c++

Ok i've been programming for about a week now, i started with c++. I'm writing a program that is a kind of an arithmetic trainer, you enter the amount of equations you want, you enter your limit for the random number generator, you specify what kind of equations you want(/*-+), then the program uses a for loop and goes through and generates the equations and their answers in a var and then the users input is checked against this var and if they match another var which is counting the right answers is incremented. After the last equation the program tells the user how many they got right out of how many equations, and by dividing the amount of right answers by the amount of questions then multiplying this value by 100 u should obtain the accuracy percentage for this users arithmetic session. Problem is c++ keeps returning to me a friggin 0 value and i cannot for the life of me work out why in the world c++ is doing this.
entire program:
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
void menu(void);
class session{
public:
session(){
create_session();
}
void create_session(void){
amount = 0;
range_limit = 0;
rights = 0;
answer = 0;
input = 0;
type = "";
while(amount == 0){
cout << "\nHow many equations do you want?: "; cin >> amount;
if(amount < 1){
cout << "\nAmount is too low!";
amount = 0;
}
}
while(range_limit == 0){
cout << "Enter the number range limit: "; cin >> range_limit;
if(range_limit < 1){
cout << "\nRange limit too low!";
range_limit = 0;
}
}
while(type == ""){
cout << "What equation type do you want?: "; cin >> type;
int strlen = type.size();
if(strlen < 1){
cout << "Invalid type input!";
type = "";
}
}
if(type == "+"){
for(int i=0;i<amount;i++){
int a = random();
int b = random();
answer = a + b;
cout << "\n" << a << " + " << b << " = "; cin >> input;
if(answer == input){
rights++;
}
}
}
cout << "\nYou got " << rights << " answers right out of " << amount << " equations." << endl;
cout << "Accuracy percentage: " << getAccuracy() << "%" << endl;
int post_menu=0;
while(post_menu == 0){
cout << "Enter 1 to create another session or 2 to return to the menu: ";
cin >> post_menu;
if(post_menu == 1){
create_session();
}else if(post_menu == 2){
menu();
}else{
cout << "Invalid input: ";
post_menu = 0;
}
}
}
float getAccuracy(){
float x = (rights/amount)*100;
return x;
}
int random(){
int x = 1+(rand()%range_limit);
return x;
}
void set_amount(int a){
amount = a;
}
void set_range_limit(int r){
range_limit = r;
}
void set_rights(int R){
rights = R;
}
void set_answer(int a){
answer = a;
}
void set_input(int i){
input = i;
}
void set_type(string t){
type = t;
}
private:
int amount;
int accuracy;
int range_limit;
int rights;
int answer;
int input;
string type;
};
int main(){
cout << "=== WELCOME TO ARITH! === \n=========================\n";
menu();
return 0;
}
void menu(void){
//Set the seed for random number gen.
srand(time(0));
//Set var for getting menu input, then get the menu input..
int menu_input;
cout << "\n[1]Create a Session. [2]Exit Arith. \nWhat would you like to do?: ";
cin >> menu_input;
//Now we check what the user wants and act accordingly..
if(menu_input > 2){
cout << "error";
menu_input=0;
}else if(menu_input == 1){
session start;
}else if(menu_input == 2){
cout << "\nExiting Arith!";
}else{
cout << "error";
menu_input=0;
}
}
Troublesome part:
float getAccuracy(){
float x = (rights/amount)*100;
return x;
some how the program is returning 0%.
anyone know why this is so and how to get the result im after.

rights and amount both are int , so when you divide the value is floored, for example if you do 5/2 the answer would be 2 instead of 2.5. To solve this you need to cast one of the variable to float like this: (float(rights)/amount) * 100.

when two int numbers are divided the result will also be int even if temporary variable. so you can make any of the variable float or double or cast it.
You need to convert only one data type because the other will be type promoted implicitly.
float x = ((double)rights/amount)*100;
or you can make your amount variable float by default if it doesnt affect any other part of your code.
Also you have the option to static cast:
float x = (static_cast<double>(rights)/amount)*100;

Related

How to stop the loop from printing the *?

I have created a project that breaks a big number to its roots, it works very well, but it prints an extra * at the end of the last root.
#include <iostream>
using namespace std;
int multinum(int a, int b);
int primeOp(int a);
int main()
{
char ch;
do {
int a=0, b=0;
multinum(a,b);
cout << "\n\nDo you want to continue?(y/n)";
cin >> ch;
} while (ch=='y');
return 0;
}
int multinum(int num1, int num2)
{
cout<< "\nPlease enter the first number : ";
cin >> num1;
cout << "\nPlease enter the second number : ";
cin >> num2;
cout << num1 <<" = ";
primeOp(num1);
cout << endl;
cout << num2 <<" = ";
primeOp(num2);
return 0;
}
int primeOp(int a)
{
int i, x, power;
x=a;
if (a%2==0)
{
power=0 ;
while(a%2==0)
{
a/=2;
power++;
}
cout << 2 <<"^"<<power<< "*";
}
for (i=3; i<=x/2; i+=2)
{
power=0 ;
while(a%i==0)
{
a/=i;
power++;
}
if (power!=0)
cout << i <<"^"<< power << "*";
if (power!=0 && a%i== 0)
cout << "*";
}
if(a==x)
cout<< x << "^" << 1;
return 0;
}
I tried to print * in different ways but none of them had any effect, I also tried to stop printing by the use of the last "i" or "power" but it was useless.
What should I do, to stop the * bring printed when it's not needed?
Example: 24 = 2^3 * 3^1 * --- it should become: 24 = 2^3*3^1
To be able to print something only sometimes you need to print it under an if, and you need a condition that will control that print. A bool flag should do the trick. The other part of the trick is to print the asterisk before the next component, not after.
void PrintComponent(int root, int power, bool& printStar)
{
if (printStar)
cout << " * ";
cout << root << "^" << power;
printStar = true;
}
int primeOp(int a)
{
int i, x, power;
bool printStar = false;
x = a;
if (a % 2 == 0)
{
...
PrintComponent(2, power, printStar);
}
for (i = 3; i <= x / 2; i += 2)
{
...
if (power != 0)
PrintComponent(i, power, printStar);
}
if (a == x)
PrintComponent(x, 1, printStar);
return 0;
}
If finding the last print is not easy make the first print special.
Print the first power like this:
cout << 2 <<"^"<<power;
Then print all the rest via
cout << "*2^"<<power;
I dont understand your code fully, but to know it is the first print you can use a boolean flag.
You can suppres this issue by printing backspaces at the end of the result.
In primeOp add:
cout <<"\b \b";
Just above return statement

How can I set this so I can't enter any more than four numbers for cin?

I'm trying to make a simple user input. I tried to set it up so there would be four numbers entered by the user. It works for four inputs from user. It does not end after four separate numbers. Also managed to find out that I can trigger an endless repeating loop if one really long number is entered. Then I have to press cntrl+C to stop the code from running. This is in Microsoft Visual Studio if that is important.
#include <iostream>
using namespace std;
void GameBoy ()
{
cout<< "\nYou think you are this badass hacker so...." <<endl;
cout<< "Please enter the correct combination of numbers..." <<endl;
int a {};
int b {};
int c {};
int d {};
cin >> a >> b >> c >> d;
double sum = a + b + c + d;
int prod = a * b * c * d;
double average = sum / 4;
cout << average << endl;
if (sum != average && average == sum)
{
cout << "You're a goober!!" << endl;
}
else
{
cout << "You're still an goober :-P" << endl;
}
}
int main()
{
while (true)
{
GameBoy ();
}
return 0;
}
You can modify your function to return bool (true if all numbers are in the correct range, false if some number is out of range). Something like this:
#include <iostream>
using namespace std;
bool GameBoy() {
cout << "\nYou think you are this badass hacker so...." << endl;
cout << "Please enter the correct combination of numbers..." << endl;
int a{};
int b{};
int c{};
int d{};
cin >> a >> b >> c >> d;
double sum = a + b + c + d;
int prod = a * b * c * d;
double average = sum / 4;
cout << average << endl;
if (sum != average && average == sum) {
cout << "You're a goober!!" << endl;
} else {
cout << "You're still an goober :-P" << endl;
}
// if (Correct condition)
// return true;
// else Wrong condition
// return false
}
int main() {
while (GameBoy()) {
}
return 0;
}
I feel silly now. Just finished posting this question and found out what I needed to stop that endless loop. Once I added this then the issue stopped. Wow won't forget that!.
cin.clear();
cin.ignore();

Calculations wont display in output

I'm a student in a basic programming class and I'm trying to complete this program for a class assignment. It's a simple program that calculates compounded interest by the inputs of the user. However, when writing the code, I noticed that the the result is 0 even though based on the input I would expect otherwise. Could anyone tell me why the program isn't showing results?
#include <iostream>
#include <cmath>
using namespace std;
// Declarations of Prototype
void futureValue(double* presentValue, float* interestRate, int* months, double* value);
// List of variables
double presentValue = 0;
float interestRate = 0;
double value = 0;
int months = 0;
// Start of Main function
int main(void)
{
cout << "What is the current value of the account?";
cin >> presentValue;
cout << "How many months will Interest be added to the account?";
cin >> months;
cout << "And what will be the Interest Rate of the account?";
cin >> interestRate;
cout << "After " << months << " months, your account balence will be $" << value << ".";
return 0;
}
void futureValue()
{
if (presentValue <= 0)
{
cout << "I'm sorry, you must have a current balence of more than 0.00 dollars to calculate.";
return;
}
else
{
value = presentValue * pow(interestRate + 1, months);
return;
}
}
Yes. You are not calling the futureValue function which would compute the value for you. Due to the value not being computed, it remains 0. Fix:
#include <iostream>
#include <cmath>
using namespace std;
// Declarations of Prototype
void futureValue(double* presentValue, float* interestRate, int* months, double* value);
// List of variables
double presentValue = 0;
float interestRate = 0;
double value = 0;
int months = 0;
// Start of Main function
int main(void)
{
cout << "What is the current value of the account?";
cin >> presentValue;
cout << "How many months will Interest be added to the account?";
cin >> months;
cout << "And what will be the Interest Rate of the account?";
cin >> interestRate;
futureValue(); //Here we compute the value
cout << "After " << months << " months, your account balence will be $" << value << ".";
return 0;
}
void futureValue()
{
if (presentValue <= 0)
{
cout << "I'm sorry, you must have a current balence of more than 0.00 dollars to calculate.";
return;
}
else
{
value = presentValue * pow(interestRate + 1, months);
return;
}
}

I keep getting a variable uninitialized error when calling a function that is asking for user input

#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
int numofEmployees();
int daysMissed(int);
int AverageMissed(int, int);
int main()
{
cout << "Welcome to employee absentee calculator!" << endl;
int numEmployees = numofEmployees();
int Missed = daysMissed(numEmployees);
double misAverage = AverageMissed(numEmployees, Missed);
cout << "There are " << numEmployees << " in the company. They have missed " << Missed << " days total. On average, they have missed " << misAverage << " days." << endl;
return 0;
}
int numofEmployees() {
cout << "How many employees are in your company? ";
int employees;
cin >> employees;
while (employees < 1) {
cout << "Employee count must 1 or greater!" << endl;
}
return employees;
}
int daysMissed(int numEmployees) {
int Absence, totAbsence = 0;
for (int i = numEmployees; i < numEmployees; i++) {
cout << "How many days has each employee missed this passed year? ";
cin >> Absence;
totAbsence += Absence;
}
while (Absence < 0) {
cout << "Values entered must be positive numbers!" << endl;
cin >> Absence;
}
return totAbsence;
}
int AverageMissed(int numEmployees, int Missed){
double Average;
Average = double(numEmployees) / double(Missed);
return Average;
}
This code is being used to calculate the average number of employee absences by way of using three functions. The second function is not working correctly as it is not being called properly by the main. This is for a school assignment.
The problem is daysMissed - if numEmployees is <= 0, then Absense will be uninitialized. But, you say, "I check that in numofEmployees" - the problem is that the compiler doesn't do that sort of whole-program analysis before issuing these warnings.
There is another problem: daysMissed is wrong (twice). If there are two employees, and I enter -2 and 1, there will be no error for the negative number. If on the other hand, if I enter 1 and -2, you never correct totAbsence. You would be much better off writing a little function which reads a number >= some limit in a loop, and keeps prompting until given the correct value. Something like:
int read(const char* prompt, const char* err_prompt, int limit) {
cout << prompt << endl;
for(;;) {
int result;
cin >> result;
if (result >= limit) {
return result;
}
cout << err_prompt << endl;
}
}
Then daysMissed becomes much pleasanter to write - and you can use the same function to read the number of employees (which will go into an infinite loop at the moment)
You should also validate a division by zero plus change the return type.
double AverageMissed(int numEmployees, int Missed){
if (Missed > 0) return double(numEmployees) / Missed;
return 0;
}
by the way, there is no need to cast both operands in the division (/). Casting one of them will be enough to return a double type.

My program for calculating the final grade doesn't calculate it and I can't tell why

I've been trying to write a C++ program that calculates your end of year grade (an exercise given by the Google for Education C++ course). The program works, except for the fact that it doesn't calculate your final grade, instead, it just outputs "0". I have searched the code and can't seem to find the problem.
#include <iostream>
using namespace std;
int check(int a) {
if (!(cin >> a)) {
cout << "Come on, that isn't a score" << endl;
return 0;
}
}
int assignments() {
int assignment1 = 0;
int assignment2 = 0;
int assignment3 = 0;
int assignment4 = 0;
cout << "Enter the score for the first assignment. ";
check(assignment1);
cout << "Enter the score for the second assignment. ";
check(assignment2);
cout << "Enter the score for the third assignment. ";
check(assignment3);
cout << "Enter the score for the fourth assignment. ";
check(assignment4);
return ((assignment1 + assignment2 + assignment3 + assignment4) / 4 * 0.4);
}
int mid() {
int midterm = 0;
cout << "Enter the score for the midterm. ";
check(midterm);
return (midterm * 0.15);
}
int finalex() {
int finals = 0;
cout << "Enter the score for the final. ";
check(finals);
return (finals * 0.35);
}
int participation() {
int parti = 0;
cout << "Enter the class participation grade. ";
check(parti);
return (parti * 0.1);
}
int main() {
int assign = assignments();
int midt = mid();
int fingra = finalex();
int partigra = participation();
cout << "The final grade is: " << assign + midt + fingra + partigra << endl;
}
(The reason I have a different program for every grade type is because the course states that you should make as many functions as possible)
Either you should pass value to check() as reference or make check to return input value.
Change
int check(int a)
to
int check(int& a)
Second method
Modify check to
int check(int a) {
if (!(cin >> a)) {
cout << "Come on, that isn't a score" << endl;
return a;
}
}
And use return value to assign input to variables. Like
int midterm = 0;
cout << "Enter the score for the midterm. ";
midterm=check(midterm);
Your cin >> a statements updates value of a local variable which is gone as soon as check() returns. You want to update value of variables that are actually used for calculating grades. Just change the function check() to pass by reference check(int &a) or pass a pointer check(int *a)