C++ Input and Output problems - c++

My problem is that when i compile and run the program, the hours doesnt have "hours" listing 1,2,3 as the loop continues and also the loop calculation is the same for each line.
this is what the program looks like
http://postimg.org/image/htk194eah/
the calculation is wrong and the hours is suppose to say 1,2...5
I would like it to look something like this
http://postimg.org/image/pnkvab1j1/
this is what i have so far:
int main()
{
// Variables
int speed;
int time;
int distance;
// Obtain the speed
cout << "Please input the speed of the vehicle " ;
cin >> speed;
while(speed < 0) // while statement
{
cout << "Please refrain from using a negative number ";
cin >> speed;
}
cout << "Please enter the time, represented in hours, travelled" <<endl;
cin >> time;
// Obtain the time
while(speed < 1)
{
cout<< "Please use a number greater than 1 " <<endl;
cin >> time;
}
// Calculation
distance = speed * time;
cout << endl;
cout << "Hour(s) " << "\t" << "Distance Travelled" << endl;
cout << "____________________________________________" << endl;
// "for" Loop statement
for(int count =1; count <= time; count++)
{
cout << " " << "\t\t" << speed*time << endl;
}
system ("PAUSE");
return 0;
}

When you print in your for loop, speed = 20 and time = 5 always, so it always prints 100 (in the example you give).
You want to be printing speed*count (in this case).
Again you print "" for the hours, which is an empty string, you want to be printing count.
cout << count << "\t\t" << speed*count << endl;

Here is the correct program. Your program was very good. But you have a very small mistake.
#include<iostream.h>
main()
{
// Variables
int speed;
int time;
int distance;
// Obtain the speed
cout << "Please input the speed of the vehicle " ;
cin >> speed;
while(speed < 0) // while statement
{
cout << "Please refrain from using a negative number ";
cin >> speed;
}
cout << "Please enter the time, represented in hours, travelled ";
cin >> time;
// Obtain the time
while(speed < 1)
{
cout<< "Please use a number greater than 1 ";
cin >> time;
}
// Calculation
cout << endl;
cout << "Hour(s) " << "\t" << "Distance Travelled" << endl;
cout << "____________________________________________" << endl;
// "for" Loop statement
for(int count =1; count <= time; count++)
{
cout << count << "\t\t" << speed * count << endl;
}
system ("PAUSE");
return 0;
}

Related

Trying to end for loop

I am trying to create a loop that allows the user to enter as many elements to the array as they would like then sum up those elements. I need the loop to terminate when the user enters a negative number. How would I go about terminating this?
double sum = 0;
double group[] = { 0 };
for (int i = 0; i >= 0; i++) {
cout << "Please enter employee salary. Enter negative number to end." << endl;
cout << "Employee " << i + 1 << ": $";
cin >> group[i];
if (i < 0) {
break;
}
sum += group[i];
}
cout << "The total salary ouput for Ernest Inc is: $" << fixed << showpoint << setprecision(2) << sum << endl;
I need the loop to terminate when the user enters a negative number.
For that a while loop would be better than for. You should also use vector which allows arbitrary number of items.
Something like this:
vector<double> group;
double salary;
while (true)
{
cout << "Please enter employee salary. Enter negative number to end." << endl;
cout << "Employee " << i + 1 << ": $";
cin >> salary;
if (salary<0)
{
break;
}
group.push_back(salary);
sum += salary;
}

Looping Confusion

My code seems to ask twice instead of once if I want to run the code again. I just want it to run normally like my other cases which only ask once after I have viewed the activity and these two activities are the only ones with problems. What seems to be the problem here:
case 5:
cout<<"Here are the list of activities in Activity 5:" << endl;
cout<<"[5.1]Determining a Number within the Array" << endl;
cout<<"[5.2]Determining the Highest and Lowest integer" << endl;
cout<<"[5.3]Reversed Array" << endl;
cin >> choice;
system("CLS");
if(choice == 5.1){
counter +=1;
int nos[10];
int det;
cout <<"Note: Do not input any decimal numbers." << endl;
for(int array = 1; array < 11; array++){
cout << "Input integers 1-10 only. [" << array << "]";
cin >> nos[det];
}
cout << "Type in 1 integer value only.[" << det << "]";
cin >> det;
if(det >= nos[1] || det <= nos[10]){
cout << "The value is within the scope of the array.";
}
else{
cout << "The value is not within the scope of the array.";
}
system ("PAUSE");
system ("CLS");
cout << "Do you want to run the program again? (y/n)" << endl;
cin >> choose;
}
else if(choice == 5.2){
counter +=1;
cout <<"Note: Do not input any decimal numbers." << endl;
cout <<"Enter your integers." << endl;
int nos[10];
int put;
for(int rep = 1; rep < 11; rep++){
cout <<"[" << rep << "]";
cin >> nos[rep];
}
int highnos = nos[1];
int lownos = nos[1];
for(int rep = 1; rep < 11; rep++){
if(nos[rep] > highnos){
highnos = nos[rep];
}
}
cout << "Your highest integer is:" << highnos << endl;
for(int rep = 1; rep > 11; rep++){
if(nos[rep] < lownos){
lownos = nos[rep];
}
}
cout <<"Your lowest integer is:"<< lownos << endl;
system ("PAUSE");
system ("CLS");
cout << "Do you want to run the program again? (y/n)" << endl;
cin >> choose;
}
P.S. my activities also has errors but dont mind it :D
First of all, you haven't initialized anything so everything is taking garbage values.
initialize det first and if you want to input the whole array then run a loop. cin>>nos[det] only inputs one value at a garbage index according to your code.
This code is a mess. Kindly fix initializations and inputs, then share the output you're getting vs the output you want.

How can I get user input to exit a loop?

I have a problem with my code, every time I loop it with the answer 'y'(Yes) it loops to infinity?
I'm trying to make a loan calculator and every time the user is done calculating with a transaction and wants to reset, and do another calculation if he enters in a value 'y', and if he enters 'n' the program will end.
Here's my code so far:
#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
char ans = 'y';
do {
string name;
int Months;
int n;
double LoanAmount, Rate, MonthlyInterest, TotalLoanAmount, MonthlyAmortization, OutstandingBalance;
cout << fixed << showpoint;
cout << "Enter Name of Borrower: ";
getline(cin, name);
cout << "Enter Loan Amount: ";
cin >> LoanAmount;
cout << "Enter Number of Months to Pay: ";
cin >> Months;
cout << "Enter Interest Rate in Percent(%): ";
cin >> Rate;
cout << setprecision(2);
MonthlyInterest = LoanAmount * Rate;
TotalLoanAmount = LoanAmount + (MonthlyInterest * Months);
cout << "Monthly Interest: " << MonthlyInterest << endl
<< "Total Loan Amount with interest: " << TotalLoanAmount << endl;
cout << setw(100)
<< "\n\tSUMMARY OF OUTSTANDING INSTALLMENT" << endl
<< "\tName of Borrower: " << name
<< "\n\nMonth\t\tMonthly Amortization\t\tOutstanding Balance"
<< "\n";
for(n = 1; n <= Months; n++) {
MonthlyAmortization = TotalLoanAmount / Months;
OutstandingBalance = TotalLoanAmount - MonthlyAmortization;
cout << n << "\t\t" << MonthlyAmortization << "\t\t\t" << n - 1 << OutstandingBalance << endl;
}
cout << "\nEnd of Transaction";
cout << "Do you want to compute another transaction?[y/n]?" << endl;
cin >> ans;
}
while(ans == 'y');
}
After your cin>>ans, add these two lines :
cin.clear();
cin.sync();
That usually fixes a lot of the infinite looping problems I get with cin.
Also, I would recommend against initializing ans as 'y' when you declare it. I don't think this is causing you problems but it's an uncessesary thing.
You seem to expect pressing y and enter to register as only 'y'. If you want to get the input of just one character have a look at std::cin.get(char)

Wrong variable in for...loop

Not a great title I know but I'm not sure how to word it. Anyway, in brief I am trying to calculate the number of scores, the total of scores and the average and grade of the scores. I am using for... loops to complete this task. So...
my function prototypes:
int validateNumber(int);
void summary(int,int,float,char);
char getGrade(float);
float getAvg(int,int);
probably only the validateNumber(int) is relevant here but just in case.
The main()
int num, total, scores;
cout << over4 << "How many scores do you want to average? " << endl;
cout << over4 << "Enter a value from 1 to 4: ";
cin >> num;
And the calls(?):
total = validateNumber(num);
summary(num,total,average,grade);
And then the definitions:
int validateNumber(int num)
{
int total = 0, score;
while (num < 1 || num > 4)
{
cout << over3 << num << " is not between 1 and 4! Try again: ";
cin >> num;
}
system("CLS");
for (int i = 1; i <= num; i++)
{
cout << over3 << "Enter score " << i << ": " << endl;
cout << over3 << "Enter a value from 0 to 100: ";
cin >> score;
while (score < 0 || score > 100)
{
cout << over3 << score << " is not between 0 and 100! Renter the score: "
<< i << ": ";
cin >> score;
}
total += score;
}
return total;
}
and:
void summary(int num,int total,float average,char grade)
{
cout << over4 << "Number of scores : " << num << endl;
cout << over4 << "Scores total : " << total << endl;
cout << over4 << "Average : " << average << "%" << endl;
cout << over4 << "Grade : " << grade << endl;
cout << down11;
}
When the user enters a num value between 1 and 4, there is no problem, the program works as it should. However when the user enters a value for num not in that range, the function works as it should BUT the summary will tell me that the number of scores was that first erroneous value and as a result mess up my average/grade.
in your function you are passing by value not by reference, so the change which is done in your function int validateNumber(int); is only in that function's scope, outside num's value is same as it was first. you should send value by reference. in this way :
int validateNumber(int &);
What happens is that you pass num to the validateNumber function by value. The local num in the validateNumber function copies the global num's value and get's processed accordingly. However, the global num variable stays as it were. In order to change the num itself you will have to pass it by reference. Change the parameters on your function definition to: int validateNumber(int &num) { ... }

Parallel Circuit

I am having trouble with this programming assignment. I need to calculate the value of total resistance for a parallel and series circuit. I have the series circuit functioning, but my problem is that when I try to calculate the total resistance for parallel circuit, my return value is 1.#INF. Any suggestions to how I can fix this
// project.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <math.h>
using namespace std;
void menu()
{
cout <<"\t\t\tLab 2 Menu Driven Algorithms" << endl;
cout <<"\t\t Calculating Parallel and Series Resistance" << endl;
cout <<"1)\tSeries" << endl;
cout <<"2)\tParallel" << endl;
cout <<"3)\tQuit" << endl;
}
int series(int& num, int& sum)
{
int answer;
num = 0;
sum = 0;
do
{
cout << "Enter Resistor " << num+1 << " value, 0 to calculate: ";
cin >> answer;
cout << endl;
sum = sum + answer;
num++;
}
while(answer != 0);
return sum;
}
double parallel (int& num, double& sum)
{
double answer;
num = 0;
sum = 0.0;
int counter = 0;
do
{
cout << "Enter Resistor " << num+1 << " value, 0 to calculate: ";
cin >> answer;
cout << endl;
counter++;
sum = (1/answer) + sum;
cout << sum << endl;
num++;
}
while(answer != 0);
return sum;
}
int main()
{
char choice;
int num = 0;
int sum = 0;
double sum2 = 0.0;
menu();
cout <<"\n\nPlease enter a value from the menu: ";
cin >> choice;
cout << endl;
while (choice != '3' && choice != 'q' && choice != 'Q')
{
switch(choice)
{
case '1': cout << "Calculating Series Resistance" << endl;
cout << "The series resistance for the " << num-1 << " resistors is: " << series(num, sum) << " Ohms\n";
system("pause");
break;
case '2': cout << "Calculating Parallel Resistance" << endl;
cout << "The parallel resistance for the " << num-1 << " resistors is: " << parallel(num, sum2) << " Ohms\n";
system("pause");
break;
default: break;
}
system("cls");
menu();
cout <<"\n\nPlease enter a value from the menu: ";
cin >> choice;
cout << endl;
}
system("pause");
return 0;
}
You probably want to rewrite the cycle inside the parallel() function this way, so that you will never process a value of 0 (which causes a division by zero in this case):
cout << "Enter Resistor " << num+1 << " value, 0 to calculate: ";
cin >> answer;
cout << endl;
while (answer != 0);
{
counter++; // NOTICE: This is never used for computation...
sum = (1/answer) + sum;
cout << sum << endl;
num++;
cout << "Enter Resistor " << num+1 << " value, 0 to calculate: ";
cin >> answer;
cout << endl;
}
The counter variable is never used for computation, so I guess you could get rid of it.
Also notice, that even the loop inside series() has a similar problem, although the fact that you never cause a division by zero doesn't make it visible.