#include <iostream>
#include <stdlib.h>
#include <string>
#include <time.h>
using namespace std;
int Round3(){
srand ( time(NULL) ); //initialize the random seed
string QNum[4];
string l,m,n,o;
QNum[0]="Name something you try to avoid when camping in the woods.";
QNum[1]="Tell me something around the house that you empty";
QNum[2]="Name something you see outdoors that rhymes with the word brain";
QNum[3]="Give me the name of a country that has exactly four letters.";
string ans1[4];
ans1[0]= "bears";
ans1[1]="bugs";
ans1[2]= "snakes";
ans1[3]="skunks";
string ans2[4];
ans2[1]="dishwasher";
ans2[0]="trashcan";
ans2[2]="ashtray";
ans2[3]="ice cube tray";
string ans3[4];
ans3[1]="rain";
ans3[0]="train";
ans3[2]="drain";
ans3[3]="plane";
string ans4[4];
ans4[1]="iraq";
ans4[0]="iran";
ans4[2]="peru";
ans4[3]="cuba";
int y;
int z;
int b;
string p1;
string p2;
string ans;
int sum=0;
int x=0;
int RandIndex = rand() % 4; //generates a random number between 0 and 3
cout << QNum[RandIndex] << endl;
if (QNum[RandIndex]==QNum[0]){
while (true){
{
cout << "Player 1, Enter your answer : ";
cin >> p1;
if (p1 == ans1[0]) {
y = 42;
}
else if (p1 == ans1[1]) {
y = 33;
}
else if (p1 == ans1[2]) {
y = 20;
}
else if (p1 == ans1[3]) {
y = 4;
}
else if (p1 != ans1[4]) {
y = 0;
}
cout << "Player 2, Enter your answer : ";
cin >> p2;
if (p2 == ans1[0]) {
z = 42;
}
else if (p2 == ans1[1]) {
z = 33;
}
else if (p2 == ans1[2]) {
z = 20;
}
else if (p2 == ans1[3]) {
z = 4;
}
else if (p2 != ans1[4]) {
z = 0;
}
}
if (y > z) {
cout << "PLAYER 1! IT'S YOUR TURN " << endl;
break;
}
else if (z>y) {
cout << "PLAYER 2! IT'S YOUR TURN" << endl;
break;
}
else if (y==z) {
cout << "Try new answers" << endl;
}
}
cout << endl;
for (int a=0; a<7; a++){
if (l==ans1[0]&&m==ans1[1]&&n==ans1[2]&&o==ans1[3]) {
continue;
}
getline(cin,ans);
if (ans==ans1[0]){
b=42; cout << "SURVEY SAYS " << b << "! Good Job! " << endl;
sum += b;
l = ans;
}
else if (ans==ans1[1]){
b = 33;
cout << "SURVEY SAYS " << b << "! Nice one man!"<< endl;
sum += b;
m = ans;
}
else if (ans==ans1[2]){
b = 20;
cout <<"SURVEY SAYS " << b << "! Fantastic man!"<< endl;
sum += b;
n = ans;
}
else if (ans==ans1[3]){
b = 4;
cout <<"SURVEY SAYS " << b << "! Fantastic man!" << endl;
sum += b;
o = ans;
}
else if (ans != ans1[0] && ans != ans1[1] && ans != ans1[2] && ans != ans1[3]){
cout << "YOU GOT THIS ONE WRONG! "<< endl; x++;
}
if (x == 4) {
cout << "You lost your turn" << endl;
break;
}
}
cout << " your total score for this round is " << sum << endl;
if (x == 4){
if (y > z) {
cout << "Player 2, What's your answer? ";
cin >> p2;
if (p2==ans1[0]) {
b=42;
sum += b;
cout << "Congratulations!correct answer! You have earned points from Player 1. Player 2 score ";
}
else if (p2 == ans1[1]) {
b = 33;
sum += b;
cout << "Congratulations!correct answer! You have earned points from Player 1.Player 2 score ";
}
else if (p2 == ans1[2]) {
b = 20;
sum += b;
cout << "Congratulations!correct answer! You have earned points from Player 1.Player 2 score ";
}
else if (p2==ans1[3]) {
b = 4;
sum += b;
cout << "Congratulations!correct answer! You have earned points from Player 1.Player 2 score ";
}
else if ( p2 != ans1[4]) {
b = 0;
cout << "WRONG! Player 1 retains their points. Player 1 score ";
}
}
else if (z > y) {
cout << "Player 1, What's your answer? ";
cin >> p1;
if (p1==ans1[0]) {
b=42;
sum += b;
cout << "Congratulations!correct answer! You have earned points from Player 1. Player 2 score ";
}
else if (p1==ans1[1]) {
b = 33;
sum += b;
cout << "Congratulations!correct answer! You have earned points from Player 1.Player 2 score ";
}
else if (p1 == ans1[2]) {
b = 20;
sum += b;
cout << "Congratulations! correct answer! You have earned points from Player 1.Player 2 score ";
}
else if (p1 == ans1[3]) {
b = 4;
sum += b;
cout << "Congratulations!correct answer! You have earned points from Player 1.Player 2 score ";
}
else if ( p1 != ans1[4]) {
b = 0;
cout << "WRONG! Player 1 retains their points. Player 1 score";
}
}
cout << "is " << sum << "." << endl;
}
}
return sum;
}
int main(){
Round3();
return 0;
}
This is just a code for one question of a game I'm creating, its family feud. Now at the end, I get the sum of scores of 1 team, but I want the sum of scores of both teams to appear separately. how do I do that?
and i want them to appear seperately so that i could get sum from all questions and then compare the scores.
You can use std::pair as return.
std::pair <std::string,double> a (var1,var2);
return a;
You can only return a single object from a function. It is not possible to return multiple objects. However, an object can have sub-objects and you can return an object whose sub-objects are the two separate results that you desire.
What you can do is define a custom type, that consists of multiple values. In C++ and in object oriented programming in general, such structure is called a class. An example class:
struct results {
int team1, team2;
};
You can define a function that returns an instance of results which contains the two values that you need.
Something you can also do is use "out variables", basically passing variables by reference to functions as arguments:
void Round3(int& team1Score, int& team2Score)
{
// Do your score calculations
team1Score = /*However you would normally calculate the score for team1*/
team2Score = /*However you would normally calculate the score for team2*/
}
It can then be used like this:
int main()
{
int score1;
int score2;
Round(score1, score2);
// score1 and score2 are now filled with the values calculated in Round3()
return 0;
}
Related
Trying to make a calculator that calculates values in an array based on input from user. But the first value in the array is always 0 when I leave 'p undefined or p = 1 will have give me the same problem. It should be whatever the user enters for the first value and so on.
#include <iostream>
using namespace std;
int main() {
double x;
int p = 1, y = 0;
double sum = 1;
int many[p];
char op;
cout << "How many numbers are you working with today?" << endl;
cin >> x;
do
{
if (y > x)
break;
cout << "Enter number " << y + 1 << ":" << endl;
cin >> many[p];
cout << "What would you like the numbers to do: (+ - / *)" << endl;
cin >> op;
if (op == '+')
{
sum+=many[p];
cout << sum <<endl;
}
else if (op == '-')
{
sum-=many[p];
cout << sum <<endl;
}
else if (op == '*')
{
sum*=many[p];
cout << sum <<endl;
}
else if (op == '/')
{
sum/=many[p];
cout << sum <<endl;
}
else {cout << "ERROR: Enter correct value." << endl;}
y++;
}
while (y < x);
}
The sum should be 3 not 4.
How many numbers are you working with today?
2
Enter number 1:
1
What would you like the numbers to do: (+ - / *)
+
Enter number 2:
2
What would you like the numbers to do: (+ - / *)
+
4
The program is invalid and has undefined behavior.
For starters variable length arrays is not a standard C+ feature
int p = 1, y = 0;
double sum = 1;
int many[p];
And in any case you defined an array with one element. So the only valid index to access elements of the array is 0.
Even in the first statement that uses the array
cin >> many[p];
it is accessed outside its bounds.
You should use the standard class template std::vector. Or as in fact you are dealing with one value then there is even no sense to use a container, Define a scalar object instead of the array.
The initial value of the sum is 1, that's why it is adding 1 more. We can't keep it 0 either, because then it will mess up the '*' and '/' cases.
I have added the initial sum value for all the cases.
Also, I would suggest you, to use switch cases instead of if, else statements.
#include <iostream>
using namespace std;
int main() {
double x;
int p = 1, y = 0;
double sum = 1;
int many[p];
char op;
cout << "How many numbers are you working with today?" << endl;
cin >> x;
do
{
if (y > x)
break;
cout << "Enter number " << y + 1 << ":" << endl;
cin >> many[p];
cout << "What would you like the numbers to do: (+ - / *)" << endl;
cin >> op;
if (op == '+')
{
if (y == 0) {
sum = 0;
}
sum+=many[p];
cout << sum <<endl;
}
else if (op == '-')
{
if (y == 0) {
sum = 0;
}
sum-=many[p];
cout << sum <<endl;
}
else if (op == '*')
{
if (y == 0) {
sum = 1;
}
sum*=many[p];
cout << sum <<endl;
}
else if (op == '/')
{
if (y == 0) {
sum = 1;
}
sum/=many[p];
cout << sum <<endl;
}
else {cout << "ERROR: Enter correct value." << endl;}
y++;
}
while (y < x);
}
There are a lot of things here that don't make sense.
You are starting with sum = 1. this is why the value is always +1
many is an array of size 1, can be changed to single int.
you are accessing many[p] which is many[1] which is out of bounds. you can only access many[0]
the rest I leave it to you to find,
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();
i have this program assignment and one part of it is trying to find the max power a number will go to(x) without exceeding a number the user inputs it not to exceed(y). we are using it in a function. this is the whole program and what i have for max power it just keeps returning 0. it is the int maxpower(int x, int y) function i am trying to figure out
#include <iostream>
#include <cmath>
using namespace std;
// meunue where you can get your options from
void menue() {
cout << "choose the following options:" << endl;
cout << "1) Power of x raised by y." << endl;
cout << "2) Find the max power a number can be raised to." << endl;
cout << "3) Print out a number with its digits in reversed order." << endl;
cout << "4) Sum of integers from 1 to n." << endl;
cout << "5) Product of integers from 1 to n." << endl;
cout << "6) Quit" << endl;
}
//functions for finding the power usign recursion
int Power(int a, int b) {
int x = 1, i;
for (i = 1; i <= b; i++) {
if (b == 0) {
return Power(a, b--);
}
else {
x = x * a;
}
}
return x;
}
int maxpower(int n, int max_value) {
int temp = temp * n;
if (temp > max_value)
return 0;
else return maxpower(n, max_value + 1);
}
int reverse(int number) {
int lastDigit, numberOfDigits, sign = 1;//sets the sign equal to one
// if number is less than 0 returns 0
if (number < 0) {
return 0;
}
else
//if a number is under 10 than it can not be switched so you times the number by 10 and switch it.
if (number < 10)
return number * sign;
lastDigit = number % 10;
number = number / 10;
numberOfDigits = log10(number) + 1;
//recursive statement that calls the function
return (lastDigit * pow(10, numberOfDigits) + reverse(number)) * sign;
}
//finding the sum
int sum(int n) {
if (n != 0) {
return n + sum(n - 1);//recursive statement
}
else {
return n;
}
}
//finding the product
int product(int n) {
int temp;
if (n <= 1) {
return 1;
}
else {
temp = n * product(n - 1);
// recursive statement setting temp == to recursive statement
return temp;//returning temp
}
}
int main() {
int a;
int x;
int y;
int length = 0;
int temp;
int results;
// calls menue and get prints all the options
do {
menue();
//inserts the choice
cin >> a;
cout << "you choose:" << a << endl;//prints the choice out.
//switch statement that will take account for the number you choose and prints the results
switch (a) {
case 1:
cout << "enter the number to raise" << endl;
cin >> x;
cout << " enter the power to raise to: " << endl;
cin >> y;
Power(x, y);
cout << "the result is:" << Power(x, y) << endl;
break;
case 2:
cout << "Enter the number to raise:" << endl;
cin >> x;
cout << "Enter the number not to exceed:" << endl;
cin >> y;
maxpower(x, y);
cout << "the result is:" << maxpower(x, y) << endl;
break;
case 3:
cout << " enter numbers to be reversed by: " << endl;
cin >> x;
temp = x;
while (temp != 0) {
length++;
temp = temp / 10;
}
reverse(x);
cout << "the result is:" << reverse(x) << endl;
break;
case 4:
cout << "enter the number to sum to: " << endl;
cin >> x;
sum(x);
cout << "the result is:" << sum(x) << endl;
break;
case 5:
cout << "enter the number to multiply to:" << endl;
cin >> y;
product(y);
cout << "the result is:" << product(y) << endl;
break;
case 6:
cout << "good bye!!" << endl;
break;
}
} while (a != 6);
return 0;
}
I don't think it's necessary to use recursion for this problem. Moreover, recursion is creating a lot of overhead while solving it with a loop works just fine. Do you have to use recursion? If so, then disregard this answer :p. But you'll find below a solution that will work.
Note the #include <math.h> bit - you need that to use pow(base, exponent).
Also, while(true) is definitely not the best practice, but as long as you have sufficient checks to get out of the loop properly then you're ok. Hence the max_iteration and the actual return statement that you're looking for.
Best of luck!
#include <iostream>
#include <math.h>
int maxpower(int n, int max_value) {
if ( n > max_value ) return 0;
int previous, current = 1;
int max_iteration = 0;
while (true) {
if (max_iteration >= 1000) return -1;
if (pow(n, current) > max_value) {
return previous;
}
previous = current;
current++;
max_iteration++;
}
}
int main() {
int x;
int y;
int result;
std::cout << "Enter the base: ";
std::cin >> x;
std::cout << "Enter the max number x^pow should not exceed: ";
std::cin >> y;
result = maxpower(x, y);
if (result == -1) {
std::cout << "Max iteration reached." << std::endl;
}
else {
std::cout << result << " is the maximum power such that " << x << "^" << result << " does not exceed " << y << std::endl;
}
return 0;
}
As an example of output:
If x = 2 and y = 32, the program will return 5 as the max power (i.e. 2^5 = 32 and is not greater than, but 2^6 > 32).
EDIT:
I realized after I posted that all of your functions are recursive, so perhaps that's a requirement for your assignment. Anyway, below is a recursive solution:
int maxpower_rec_helper(int n, int power, int max_value) {
if (pow(n, power) > max_value) return power - 1;
return maxpower_rec_helper(n, power + 1, max_value);
}
int maxpower_rec(int n, int max_value) {
if ( n > max_value ) return 0;
return maxpower_rec_helper(n, 1, max_value);
}
You'll need a helper function to give the initial power 1, and so as not to disturb your max_value.
return power - 1; is essentially the same thing as return previous; in the iterative example above.
We're only interested in the #'s in the range [0,100]. There may be number outside the range [0, 100], but they aren't part of our calculation (i.e numbers below 0 and above 100 can be inputted but will be ignored in the calculations and counters).
Assume we assign ABCDF as
[85,100]: A
[75,85): B
[65,75): C
[55,65): D
[0,55): F
For each of the five letter grades, output the number of scores with that grade, and also, if the number of scores wasn't 0, output the average score with that grade. Also, if the number of valid scores (in [0, 100]) wasn't 0, output the average of all the scores
I am having trouble with this looping question. When I input multiple scores, it loops them incorrectly and outputs two sets of grades for each input rather than the example answer shown above. Also I am not sure if my break is placed correctly to exit the program when a word is inputted. Any help will be greatly appreciated!
Here is my code:
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <string>
using namespace std;
int main(){
double scores;
unsigned countA = 0;
unsigned countB = 0;
unsigned countC = 0;
unsigned countD = 0;
unsigned countF = 0;
char grade;
double sumA = 0, sumB = 0, sumC = 0, sumD = 0, sumF = 0;
cout << "Enter scores: ";
for (scores; cin >> scores;){
if (scores > 85 && scores <= 100){
grade = 'A';
countA++;
sumA += scores;
}
else if (scores > 75){
grade = 'B';
countB++;
sumB += scores;
}
else if (scores > 65){
grade = 'C';
countC++;
sumC += scores;
}
else if (scores > 55){
grade = 'D';
countD++;
sumD += scores;
}
else{
grade = 'F';
countF++;
sumF += scores;
}
if (!cin){
break;
}
if (countA == 0){
cout << "# A's: 0 " << endl;
}
else {
cout << "# A's: " << countA << " Average = " << sumA/countA << endl;
} if (countB == 0){
cout << "# B's : 0 " << endl;
}
else{
cout << "# B's: " << countB << " Average = " << sumB /countB << endl;
} if (countC == 0){
cout << "# C's: 0 " << endl;
}
else{
cout << "# C's: " << countC << " Average = " << sumC /countC << endl;
} if (countD == 0){
cout << "# D's: 0 " << endl;
}
else {
cout << "# D's: " << countD << " Average = " << sumD /countD << endl;
} if (countF == 0){
cout << "# F's: 0 " << endl;
}
else {
cout << "# F's: " << countF << " Average = " << sumF /countF << endl;
}
}
TL;DR version: Closing brace on the for loop was missing. Loop never ended and caused OP's output code to also loop.
Long version:
Here is working code. The stuff I changed is marked with comments.
#include <iostream> //removed a bunch of unused includes.
using std::cin; // including all of namespace::std is overkill and often
using std::cout; // leads to hard-to-solve bugs. Only use what you need
using std::endl;
int main()
{
double scores;
unsigned countA = 0;
unsigned countB = 0;
unsigned countC = 0;
unsigned countD = 0;
unsigned countF = 0;
char grade;
double sumA = 0, sumB = 0, sumC = 0, sumD = 0, sumF = 0;
cout << "Enter scores: ";
// for (scores; cin >> scores;){
while (cin >> scores) // cleaner
{
if (scores > 85 && scores <= 100)
{
grade = 'A';
countA++;
sumA += scores;
}
else if (scores > 75)
{
grade = 'B';
countB++;
sumB += scores;
}
else if (scores > 65)
{
grade = 'C';
countC++;
sumC += scores;
}
else if (scores > 55)
{
grade = 'D';
countD++;
sumD += scores;
}
else
{
grade = 'F';
countF++;
sumF += scores;
}
// this test is made redundant by the loop condition
// if (!cin)
// {
// break;
// }
} // this was missing. The loop kept going and included all of
// the following code in the loop.
if (countA == 0)
{
cout << "# A's: 0 " << endl;
}
else
{
cout << "# A's: " << countA << " Average = " << sumA / countA << endl;
}
if (countB == 0)
{
cout << "# B's : 0 " << endl;
}
else
{
cout << "# B's: " << countB << " Average = " << sumB / countB << endl;
}
if (countC == 0)
{
cout << "# C's: 0 " << endl;
}
else
{
cout << "# C's: " << countC << " Average = " << sumC / countC << endl;
}
if (countD == 0)
{
cout << "# D's: 0 " << endl;
}
else
{
cout << "# D's: " << countD << " Average = " << sumD / countD << endl;
}
if (countF == 0)
{
cout << "# F's: 0 " << endl;
}
else
{
cout << "# F's: " << countF << " Average = " << sumF / countF << endl;
}
}
Your question is a bit confusing, I assume your main issue is the output part. Currently your code produces this.
As you see we get intermediate output, after every score entered. To change that the loop needs to be split into two loops: One for input, and one for output that runs after the first:
while (/* we get scores */) {
// update the counters and sums
}
for (/* every score */) {
// print count and average
}
To generate the output in a loop you need to store your data in some "loopable" way. Currently you have multiple local variables. Changing that to an array (indexed by the respective grade) allows us to loop over the data:
unsigned counter[5];
double sum [5];
// A -> 0, B -> 1, ..., F -> 4
for (std::size_t it = 0; it < 5; ++it) {
// use sum[it] and counter[it]
}
But raw arrays (as raw pointers) are evil - only use them when absolutely necessary - we use std::array from the standard library. And to ease iteration and improve logical encapsulation it's good to keep sum and count of each grade together:
struct grade_info {
unsigned count = 0;
double sum = 0;
};
// ... later in the main function
std::array<grade_info, 5> grades;
// input
for (auto const & grade : grades) { // C++11 shorthand to iterate over a collection
// use grade.count and grade.sum
}
Concerning your input:
for (scores; cin >> scores;){
This does the right thing, but is a bit strange. Since scores will only be used inside that loop instead of declaring it as local variable of main we only declare it inside the loop:
for (double score; // only a single score is in that variable at any time
cin >> score; // ends the loop on eof or failure to convert to double (when text got entered)
// no step instructions, the above check does that already
) {
Now there's also no need to test cin inside the loop. The operator>> returns (a reference to) its first argument, which is cin, so the test in the for loop already tests cin, no need for if (! cin) { break; }.
Then you have code like this
grade = 'A';
when you never use the value stored in grade. Just remove that.
Last but not least your input validation isn't working (the 101 in my test case is treated as grade B):
if (scores > 85 && scores <= 100) {
// scores between (85, 100]
}
// scores is either <= 85 OR > 100
else if (scores > 75){
// scores is in (75, 85] OR > 100
}
Ideally you should keep input validation and business logic separated:
if (not input_is_valid(score)) {
continue; // the loop
}
// business logic, assuming valid input
So, the final code could be
#include <iostream>
#include <array>
struct grade_info {
unsigned count = 0;
double sum = 0;
char const name;
grade_info(char n) : name(n) {
}
};
bool input_is_valid(double score) {
return (score >= 0) and (score <= 100);
}
std::size_t score_to_grade_index(double score) {
if (score >= 85) {
return 0;
} else if (score >= 75) {
return 1;
} else if (score >= 65) {
return 2;
} else if (score >= 55) {
return 3;
} else {
return 4;
}
}
int main(int, char**) {
std::array<grade_info, 5> grades {'A', 'B', 'C', 'D', 'F'};
for (double score; std::cin >> score;) {
if (not input_is_valid(score)) {
continue;
}
auto index = score_to_grade_index(score);
++(grades[index].count);
grades[index].sum += score;
}
for (auto const & grade : grades) {
std::cout << "# " << grade.name << ": "
<< grade.count;
if (grade.count > 0) {
std::cout << " avg: " << (grade.sum / grade.count);
}
std::cout << std::endl;
}
return 0;
}
Live here
I just started learning c++
In this program i try two categorize two resistors based on their values
but at the end i cant print out correctly the x but only the part before ,
for example i tried r1=0 r2=50 r3=100 r4=60 V=9 n=4 1st value=55 2nd=56 3rd=52 4th=57 x should be 56*57/(56+57)=28.24778761 but i only get 28 why?
#include <iostream>
using namespace std;
int main()
{
int n;
float V, TOTAL1, TOTAL2, y;
int r1, r2, r3, r4, i;
cout << "Give r1: "; // Ask for resistors.
cin >> r1;
cout << "Give r2: ";
cin >> r2;
cout << "Give r3: ";
cin >> r3;
cout << "Give r4: ";
cin >> r4;
cout << "Give voltage: ";
cin >> V;
cout << "Give number of resistors: ";
cin >> n;
int a, b; // Ccount the number on its category.
int m;
m = 0;
a = 0;
b = 0;
y = 0;
TOTAL2 = 0;
for(i = 1; i < n + 1; i++)
{
y = TOTAL2 + y; // Calculate the as they are in series
float value;
m = m + 1;
cout << "\n Give resistance: ";
cin >> value;
if((value >= r1) && (value >= r2) && (value <= r3) && (value <= r4))
{
if(m % 2>0)
{
cout << "It belongs to the first";
a = a + 1;
TOTAL1 = value + TOTAL1; // If they are in the first category they are connected in series
}
else
{
cout << "It belongs to the second";
b = b + 1;
TOTAL2 = 1 / value;
}
}
else if((value >= r1) && (value <= r2)){
cout << "It belongs to the first";
a = a + 1;
TOTAL1 = value + TOTAL1;
}
else if((value >= r3) && (value <= r4)) {
cout << "It belongs to the second";
b = b + 1;
TOTAL2 = 1 / value + 1 / TOTAL2;
}
}
long double x;
x = 1 / y;
cout << "\n The first category has: " << a;
cout << "\n The second category has: " << b;
cout << "\n The total resistance of the first category is: " << TOTAL1;
cout << "\n The total resistance of the second category is: " << x;
return 0;
}
The variable y is only updated at the top of the loop, so the last update is lost. So y contains 1/28 (the first value), and when you take its reciprocal, you get 28 exactly.