I am trying to add two floats in a for loop and its telling me '+' has no affect. I am attempting to make it parse through each incrememnt (.25) of the two ranges (begrate and endrate) (1 and 2) and 1+.25 is not working correctly and I get an infinite loop
float begrate,endrate,inc,year=0;
cout << "Monthly Payment Factors used in Compute Monthly Payments!" << endl;
cout << "Enter Interest Rate Range and Increment" << endl;
cout << "Enter the Beginning of the Interest Range: ";
cin >> begrate;
cout << "Enter the Ending of the Interest Range: ";
cin >> endrate;
cout << "Enter the Increment of the Interest Range: ";
cin >> inc;
cout << "Enter the Year Range in Years: ";
cin >> year;
cout << endl;
for (float i=1;i<year;i++){
cout << "Year: " << " ";
for(begrate;begrate<endrate;begrate+inc){
cout << "Test " << begrate << endl;
}
}
system("pause");
return 0;
That's because begrate+inc has no effect on the value of begrate. The + operator is not like the ++ operator. You must assign the results to something to have an effect. What you wanted is this:
begrate = begrate + inc
Or
begrate += inc
You could use += instead of +, as this will set begrate to begrate+inc. The better solution would be to have a temporary loop variable that starts equal to begrate then increment it.
for (float i=1;i<year;i++){
cout << "Year: " << " ";
for(float j = begrate;j<endrate;j+=inc){
cout << "Test " << j << endl;
}
}
Just replace the following line
for(begrate;begrate<endrate;begrate+inc){
with
for(begrate;begrate<endrate;begrate+=inc){
notice the begrate*+=*inc here
Related
I'm trying to automatically set the number of the given variables, for example:
char subject1[30];
char subject2[30];
char subject3[30];
float grade1;
float grade2;
float grade3;
cout << "Type in your first subject: " ;
cin >> subject1;
cout << "Type in your second subject: ";
cin >> subject2;
cout << "Type in your third subject: ";
cin >> subject3;
cout << "Type in your grade for: " << subject1 << " :";
cin >> grade1;
cout << "Type in your grade for: " << subject2 << " :";
cin >> grade2;
cout << "Type in your grade for: " << subject3 << " :";
cin >> grade3;
float sum = grade1 + grade2 + grade3;
float average = (sum / 3);
cout << "AVERAGE GRADE";
cout << "************************************" << endl;
cout << subject1 << grade1 << endl;
cout << subject2 << grade2 << endl;
cout << subject3 << grade3 << endl;
cout << "====================================" << endl;
cout << "Average: " << average << endl;
return 0;
The code that calculates it works but I was wondering as how do I put the 3 grades that user inputed. So I don't have to go edit the calculation part every time I add another subject. I'm not sure if I explained well as to what I meant but I hope you understand.
A simple solution would be to store everything in a vector (that's preferred most of the time over the char array you used) an then just loop for the amount of subjects you have.
#include <vector> // need to inlcude this to be able to use vector
#include <iostream>
const int numSubjects = 3;
std::vector<std::string> prefix{"first", "second", "third"};
std::vector<std::string> subjects(numSubjects);
std::vector<float> grades(numSubjects);
for(int i = 0; i < numSubjects; i++) {
std::cout << "Type in your " << prefix[i] << " subject: ";
std::cin >> subjects[i];
std::cout << "Type in your grade for " << subjects[i] << ": ";
std::cin >> grades[i];
}
//afterwards do the calculations
Note that I initialized the vectors with a size of numSubjects that way you can access and write to indices of the vector with the [] operator. If you don't initialize vector with a size then you can use push_back() to insert elements.
I wrote this code to basically shuffle a vector and I'm getting this error, and I'm not sure what's wrong. I have included algorithm. Thank you!
// Shuffle the vector
random_shuffle(names.begin(), names.end(), rand());
// Prelims
cout << "ROUND PRELIMINATION: BEGIN" << endl;
cout << names[32] << " versus " << names[29] << endl << "Please enter the winner: ";
cin >> winner;
round1.push_back(winner);
cout << endl << names[33] << " versus " << names[30] << endl << "Please enter the winner: ";
cin >> winner;
round1.push_back(winner);
cout << endl << names[34] << " versus " << names[31] << endl << "Please enter the winner: ";
cin >> winner;
round1.push_back(winner);
for (int i = 0; i < 29; i++) {
round1.push_back(names[i]);
}
The last argument to random_shuffle needs to be a function object returning a randomly chosen value. rand() evaluates to an int. Hence, it cannot be used as the last argument to the function.
The following should work.
// Shuffle the vector
random_shuffle(names.begin(), names.end(), [](int n) { return rand()%n; });
I'm trying to complete an assignment but I'm having difficulty with the math expressions and variables in general. I'm trying to make a program that takes user info on groceries and then outputs a receipt. Here is my code.
#include <iostream>
#include <string>
using namespace std;
int main()
{
//user input
string firstItem, secondItem;
float firstPrice, secondPrice;
int firstCount, secondCount;
double salesTax = 0.08675;
double firstExt = firstPrice * firstCount;
double secondExt = secondPrice * secondCount;
double subTotal = firstExt + secondExt;
double tax = subTotal * salesTax;
double total = tax + subTotal;
//user input
cout << "What is the first item you are buying?" << endl;
getline(cin, firstItem);
cout << "What is the price of the " << firstItem << "?" << endl;
cin >> firstPrice;
cout << "How many " << firstItem << "s?" <<endl;
cin >> firstCount;
cin.ignore();
cout << "What is the second item you are buying?" << endl;
getline(cin, secondItem);
cout << "what is the price of the " << secondItem << "?" << endl;
cin >> secondPrice;
cout << "How many " << secondItem << "s?" << endl;
cin >> secondCount;
// receipt output
cout << "1st extended price: " << firstExt << endl;
cout << "2nd extended price: " << secondExt << endl;
cout << "subtotal: " << subTotal << endl;
cout << "tax: " << tax << endl;
cout << "total: " << total << endl;
return 0;
}
The program output either 0 for all or negatives.
Your calculations must go after you read in the values, not before. You're making your calculations based on uninitialized variables.
A declaration and initialisation like
double firstExt = firstPrice * firstCount;
initialises firstExt to be the product of the current values AT THAT POINT of firstPrice and firstCount.
It doesn't set up some magic so that the value of firstExt is recalculated whenever the values of firstPrice or firstCount are changed.
In your case, firstPrice and firstCount are uninitialised variables when you do this. Accessing values of uninitialised variables of type int gives undefined behaviour.
What you need to do is something like
cout << "What is the price of the " << firstItem << "?" << endl;
cin >> firstPrice;
cout << "How many " << firstItem << "s?" <<endl;
cin >> firstCount;
firstExt = firstPrice*firstCount; // do the calculation here
If the value of firstExt is not needed until this point, you can declare it here instead;
double firstExt = firstPrice*firstCount; // do the calculation here
which means any earlier use of firstExt will give a compiler diagnostic.
My program runs the first For loop correctly then skips the Cin's on the 2nd and 3rd cycle. Then when the loop is finished it goes on to calculate the BMI of the first index [0] and does this correctly and gives the right answer but then nothing for the index's 1 and [2] because no information was inputted because the cin's were skipped.
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
struct Patient
{
double height;
double weight;
int age;
bool isMale;
};
int main()
{
Patient Patients[3];
for (int i = 0; i < 3; i++) {
cout << "Patient "<< i << " Height: ";
cin >> Patients[i].height;
cout << "Patient " << i << " Weight: ";
cin >> Patients[i].weight;
cout << "Patient " << i << " Age: ";
cin >> Patients[i].age;
cout << "Is Patient " << i << " Male True or False: ";
cin >> Patients[i].isMale;
cout << endl << endl;
}
cout << endl << endl;
for (int i = 0; i < 3; i++) {
float BMI = Patients[i].weight / (Patients[i].height *Patients[i].height);
cout << "Patient " << i << " Has A BMI of: " << BMI << endl << endl;
}
return 0;
}
This is the console where you can see after the first loop all the cin's are skipped but the first loop was correctly stored as it couted the BMI of the first index:
You see that you are having an error at the end of the loop. You can see from iterations 2 and 3 that cin is not behaving the same way each time. There are a couple of error state flags that come from ios that will help you see what's going wrong here. See iso::good for details. If you add those checks:
for (int i = 0; i < 3; i++) {
cout << "Patient " << i << " Height: ";
cin >> Patients[i].height;
cout << "Patient " << i << " Weight: ";
cin >> Patients[i].weight;
cout << "Patient " << i << " Age: ";
cin >> Patients[i].age;
cout << "Is Patient " << i << " Male True or False: ";
cin >> Patients[i].isMale;
cout << cin.good() << '\n';
cout << cin.eof() << '\n';
cout << cin.fail() << '\n';
cout << cin.bad() << '\n';
cout << endl << endl;
}
What you will see if that cin is no longer good, it is not eof it is fail, and it is not bad. While the fail bit is set, cin will not work. Hence you see the result. Looking at the chart in the link you see this:
Logical error on i/o operation
You were preforming an i/o operation of inserting "true" into a bool. The word true is probably stored as a character array or string, not a boolean. How should cin convert this to a boolean? You need to trap your input and convert it into a bool or switch to use an input that can be explicitly converted into a bool.
For example:
cout << "Is Patient " << i << " Male? (1 for Male, 0 for Female):";
cin >> Patients[i].isMale;
In this case the cin recognizes 1 and 0 as integers and can convert an integer into a boolean. 0 is false, everything else is true. Another option is to let the library do it and use boolalpha. You can read about it here.
This shows a larger issue. What happens if I write "two point five" as the answer to height? In this case we can assume some intelligence on the part of the user, but thinking about things like this will help write more robust code in the future.
You can fix your program in two ways.
Just input "0" or "1" in the male/female question instead of "true" or "false".
Change this line and continue to input "true" or "false":
cin >> boolalpha >> Patients[i].isMale;
Sources:
Cin and Boolean input
http://www.cplusplus.com/reference/ios/boolalpha/
How do you check for non-numeric input using C++? I am using cin to read in a float value, and I want to check if non-numerical input is entered via stdin. I have tried to use scanf using the %d designator, but my output was corrupted. When using cin, I get the correct format, but when I enter, a string such as "dsffsw", I get an infinite loop.
The commented code was my attempt to capture the float, and type cast it as string, and check if it is a valid float, but the check always comes up false.
I have tried using other methods I have found on the message boards, but they want to use scanf in C and not cin in C++. How do you do this in C++? Or in C if it is not feasible.
while (!flag) {
cout << "Enter amount:" << endl;
cin >> amount;
cout << "BEGIN The amount you entered is: " << strtod(&end,&pend) << endl;
//if (!strtod(((const char *)&amount), NULL)) {
// cout << "This is not a float!" << endl;
// cout << "i = " << strtod(((const char *)&amount), NULL) << endl;
// //amount = 0.0;
//}
change = (int) ceil(amount * 100);
cout << "change = " << change << endl;
cout << "100s= " << change/100 << endl;
change %= 100;
cout << "25s= " << change/25 << endl;
change %= 25;
cout << "10s= " << change/10 << endl;
change %= 10;
cout << "5s= " << change/5 << endl;
change %= 5;
cout << "1s= " << change << endl;
cout << "END The amount you entered is: " << amount << endl;
}
return 0;
}
int amount;
cout << "Enter amount:" << endl;
while(!(cin >> amount)) {
string garbage;
cin.clear();
getline(cin,garbage);
cout << "Invalid amount. "
<< "Enter Numeric value for amount:" << endl;
}
I think you task relates to the so called defensive programming, one of it`s ideas is to prevent situations like one you described (function expects one type and user enters another).
I offer you to judge whether input is correct using method that returns stream state , which is good(),
so I think it will look something like this:
int amount = 0;
while (cin.good()) {
cout << "Enter amount:" << endl;
cin >> amount;