Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I need to write a program that would read in numbers from the keyboard, compute the average of the numbers, and display it. The sequence of numbers are to be terminated with a zero.
Here is my code:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
int count;
double number, sum, average;
count = 0;
sum = 0;
average = 0;
cout << "\nEnter Number (0 to terminate): ";
cin >> number;
while(number! = 0.0)
{
sum = sum + number;
count = count + 1;
cout << "\nEnter Number: ";
cin >> number;
}
if(count! = 0.0);
{
average = sum/count;
}
cout << "\nThe average of the" << count << "number is" << average << endl;
return 0;
}
However, I am getting two errors:
expected ')'
and
if statement has empty body
if(count! = 0.0);
Get rid of semicolon
There are three errors:
The != operator is mis-spelled ! = in two places.
The if has a semicolon after the closing parentheses.
Please do not insert any whitespaces between your comparators.
You wrote (number! = 0.0), but the correct one should be: (number != 0.0).
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
int count;
double number, sum, average;
count = 0;
sum = 0;
average = 0;
cout << "\nEnter Number (0 to terminate): ";
cin >> number;
while(number != 0.0)
{
sum = sum + number;
count = count + 1;
cout << "\nEnter Number: ";
cin >> number;
}
if(count != 0.0)
{
average = sum/count;
}
cout << "\nThe average of the" << count << "number is" << average << endl;
return 0;
}
You have a semi-colon (;) right after the if statement. Remove it :)
if(count! = 0.0)
while(number! = 0.0) should be while(number != 0.0)
and
if(count! = 0.0) should be if(count != 0.0)
Note != is an operator but ! = is not - attention to the details!
Related
I'm trying to write a program that reads in positive float numbers from the user and then when the user's is a negative number, gives the average of the numbers, excluding the negative.
#include <iostream>
using namespace std;
int main() {
float av_number, total = 0, input;
do {
for (int i = 1; i >= 1; i = ++i) {
cout << "Please input a number: ";
cin >> input;
total = total += input;
av_number = total / i;
cout << av_number << endl;
break;
}
} while (input >= 0);
cout << av_number << endl;
}
When I run this, the program simply adds the inputs together on each line, and then subtracts my final negative input before closing the program.
If I were to guess, It's likely a logical confliction within my sequence of do & for loops, but I'm unable to identify the issue. I may have also misused i in some fashion, but I'm not certain precisely how.
Any help would be appreciated as I'm still learning, Cheers!
you don't need the for loop, you just need some iterator to count the number of entered numbers, so you can delete that for loop and use a counter variable instead.
also, you are breaking in the loop without checking if the input < 0, so you can write this
if (input < 0)
break;
also, you shouldn't calculate av_number = total / counter; except only after the end of the big while loop
it's total += input; not total = total += input;
writing while (input >= 0) wouldn't make sense as long as you are breaking inside the loop when input < 0, so you can write while (true); instead
and this is the code edited:
#include <iostream>
using namespace std;
int main() {
float av_number = 1.0, total = 1, input = 1.0;
int counter = 0;
do {
cout << "Please input a number: ";
cin >> input;
if (input < 0)
break;
counter++;
total += input;
} while (true);
av_number = total / counter;
cout << av_number << endl;
}
and this is the output:
Please input a number: 5
Please input a number: 12
Please input a number: 7
Please input a number: -2
8
P.S : read more about Why is "using namespace std;" considered bad practice?
You should move the calculation of the average value out of the loop where the adding takes place and only add non-negative values to total.
#include <iostream>
int main() {
float total = 0.f;
int i = 0;
// loop for as long as the user successfully enters a non-negative value:
for (float input; std::cout << "Please input a number: " &&
std::cin >> input &&
!(input < 0.f); ++i)
{
// now `input` is non-negative
total += input; // and only sum it up here, no average calculation
}
if (i > 0) { // avoid division by zero
// finally calculate the average:
float av_number = total / i;
std::cout << av_number << '\n';
}
}
The condition for the loop is that std::cout << "Please input a number: " succeeds and that std::cin >> input succeeds and that input is not less than zero.
In one of my c++ class assignments, I was given the task:
Write a program that reads in a list of floating-point numbers and then prints out the count of the values, the average, and the standard deviation.
You can assume that the the user's input is always valid and that the list contains at least two numbers.
You can assume that the numbers in the list are separated by one space character and that the character following the last number in the list is the newline character.
Implement a loop in which the above actions are repeated until the user requests to quit.
I am struggling with the last step, where I need to ask the user if they want to continue. My code is as follow.
#include <iostream>
#include <algorithm>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
char counter;
do {
char ch = ' ';
int i = 0;
double sum = 0;
double average = 0;
double sum_squared = 0;
cout << "Please enter a list of values (of type double): ";
do {
double x;
cin >> x;
ch = cin.get();
i += 1;
sum += x;
double x_squared = pow(x, 2);
sum_squared += x_squared;
} while (ch != '\n');
average = sum / i;
double standard_deviation = sqrt((sum_squared - (pow(sum, 2) / i)) / (i - 1));
cout << "Number = " << i << endl;
cout << "Average = " << average << endl;
cout << "Standard deviation = " << standard_deviation << endl;
cout << "Continue? (y,n) "; cin >> counter;
} while (counter = 'y');
return 0;
}
I was expecting that when user enter y in the end, the program would re-execute. But it turned out to be weird. When I enter n, the code still re-execute. Can anyone explain why? Additionally, how do I correctly implement this function to my code? Thank you all for your help and response.
changing
counter = 'y'
to
counter == 'y'
near the end will yield the satisfactory result.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I am having a hard time trying to add the starting value with the increment value up until it reaches the ending value or it cant add again because it would exceed the max value(the end value).
Ok I am just going to get straight to it, here is my assignment.
In this assignment, you will complete a C++ program that sums up the integers in a range of values and prints the result. This will be done two different ways: using a while loop and using a for loop.
For this assignment, you have more freedom in choosing the local variables that you need to declare and in figuring out what source code to write. However, your program needs to follow the coding standards of this course and fulfill the software requirements described in the next section.
Below is an example execution of the program. In this case, the program added up the numbers 8, 25, 42, 59, 76, 93, and 110. Your program shall follow the same format shown below for prompting the user and printing the results.
Enter a starting integer value: 8
Enter an ending integer value: 121
Enter a positive increment: 17
Sum (using a while loop): 413
Sum (using a for loop): 413
Here is what I have for code so far
#include <iostream>
using namespace std;
int main(){
//while loop sum
int sumw = 0;
//for loop sum
int sumf = 0;
//starting integer
int nums;
//ending integer
int nume;
//increment integer
int numi;
cout <<"Please enter a starting value: " << endl;
cin >> nums;
cout <<"Please enter an ending value: " << endl;
cin >> nume;
cout <<"Please enter a positive increment value: " << endl;
cin >> numi;
if (numi <= 0 || nums > nume) cout << "Error ";
if (numi <= 0 || nums > nume) return 0;
for (int i = 1; i <= numi; i++){
sumf =+ numi;
}
cout << "Sum(using for loop): " << sumf;
return 0;
}
If someone could help me with this that would be great!!! Thank you!!
This is probably what you are looking for
for (int i = nums; i <= nume; i = (i + numi)){
sumf += i;
}
Start with nums until you are less than or equal to nume and increment i in steps of numi i.e. i = i + numi
Additionally, you can combine:
if (numi <= 0 || nums > nume) cout << "Error ";
if (numi <= 0 || nums > nume) return 0;
to
if (numi <= 0 || nums > nume){
cout << "Error ";
return 0;
}
Assumed the starting number as greater than or equal to 1(>=1).
Using while loop:
#include <iostream>
using namespace std;
int main()
{
int totalSum = 0, startingNumber, endingNumber, positiveIncrement;
cout <<"Enter the starting number: " << endl;
cin >> startingNumber;
cout <<"Enter the ending number: " << endl;
cin >> endingNumber;
cout <<"Enter the positive increment: " << endl;
cin >> positiveIncrement;
if ((startingNumber <= 0) || (startingNumber > endingNumber))
{
cout<<"Error in input provided"<< endl;
return 0;
}
totalSum = startingNumber;
while ((startingNumber + positiveIncrement) <= endingNumber)
{
startingNumber += positiveIncrement;
totalSum += startingNumber;
}
cout << "Total Sum = " << totalSum;
return 0;
}
Using for loop:
#include <iostream>
using namespace std;
int main()
{
int totalSum = 0, startingNumber, endingNumber, positiveIncrement;
cout <<"Enter the starting number: " << endl;
cin >> startingNumber;
cout <<"Enter the ending number: " << endl;
cin >> endingNumber;
cout <<"Enter the positive increment: " << endl;
cin >> positiveIncrement;
if ((startingNumber <= 0) || (startingNumber > endingNumber))
{
cout<<"Error in input provided"<< endl;
return 0;
}
for ((totalSum = startingNumber);((startingNumber + positiveIncrement) <= endingNumber);(startingNumber += positiveIncrement))
{
totalSum += (startingNumber+positiveIncrement);
}
cout << "Total Sum = " << totalSum;
return 0;
}
See definition of for statement in a good reference:
for ( initializer, terminating condition, increment)
The third parameter is the increment.
You could do something like:
for (int i = nums; i < nume; i = i + numi)
{
}
Inside the loop, you'll have figure out what you need to sum and how to do it.
welcome to the world of computer science and programming :)
several points:
it is unclear what it is you need help with, posting your assignment is not a good way to get help. with your next question, try using this as a guide line on how to ask a question: https://stackoverflow.com/help/how-to-ask
here is a list of operators in C++, and how to use them, https://www.geeksforgeeks.org/operators-c-c/ you will notice =+ is not there, becuase it is not a valid operator.
what you do have, is:
“+=”:This operator is combination of ‘+’ and ‘=’ operators. This
operator first adds the current value of the variable on left to the
value on right and then assigns the result to the variable on the
left.
Example: (a += b) can be written as (a = a + b)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
TASK 2 remains un-executed. Task 1 works fine, I input the yield values of the cows; but then the code stops running. A warning says that Herdtotalweek may be uninitialized. But I don't know how to fix that. There are no other warnings or errors.
#include <iostream>
#include <string>
using namespace std;
int main() { //Task 1
int Herdsize;
int Day;
float MilkYield1;
float MilkYield2;
int count;
cout << "Please input herd size" << endl;
cin >> Herdsize;
while (Herdsize < 1 || Herdsize > 900) {
cout << "Please re-input herdsize between 1 and 900" << endl;
cin >> Herdsize;
}
int CowID[Herdsize + 1];
float DailyYield[Herdsize * 7];
float WeeklyYieldpercow[Herdsize * 14];
for (count = 1; count < Herdsize + 1; count++) {
cout << "Input 3 digit cow id ";
cin >> CowID[count];
while (CowID[count] < 1 || CowID[count] > 999) {
cout << "Please re-input cow a 3 digit cow id " << endl;
cin >> CowID[count];
}
for (Day = 1; Day < 8; Day++) {
cout << "Please input first milk yield of cow,day";
cout << Day;
cout << endl;
cin >> MilkYield1;
cout << "Please input second milk yield day:";
cout << Day;
cout << ", if there is a second yield if not enter 0";
cout << endl;
cin >> MilkYield2;
}
DailyYield[((count - 1) * 7) + Day] = MilkYield1 + MilkYield2;
WeeklyYieldpercow[count] = WeeklyYieldpercow[count] +
DailyYield[((count - 1) * 7) + Day];
}
// TASK 2
int count2 = 1;
float Herdtotalweek;
float Averagevolume;
for (count = 1; count2 < Herdsize + 1; count++) {
Herdtotalweek = Herdtotalweek + WeeklyYieldpercow[count];
}
Averagevolume = Herdtotalweek / Herdsize;
int Herdtotalweekwhole = int(Herdtotalweek + 0.5);
int Averagevolumewhole = int(Averagevolume + 0.5);
cout << "Total weekly volume=";
cout << Herdtotalweekwhole;
cout << "Average volume =";
cout << Averagevolumewhole;
}
instead of float Herdtotalweek; try using float Herdtotalweek = 0; ?
also, in your second for statement, instead of for (count=1;count2<Herdsize+1;count++) try for (count=1;count<Herdsize+1;count++) (you were using count2 instead of count, which was probably a copy/paste error)
The for loop after task2 never completes. It is an infinite loop as you are not updating count2.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
This program accepts input of the everyday prices of a good and then calculates the greatest profit. And the list of prices will end with -1.
for example, if I input 20,30,10,50,-1 , it means at the first day the good is $20,in the second day is $30,etc. The greatest profit output will be $40 since I could buy it on the third day at $10 and sell it in the fourth day at $50.
This is a school assignment and the teacher do not allow me to use array.
Now my program is fine except in this case e.g.
if I input 20 30 10, the greatest profit will be $(30-10) how could I fix it so if will not store the number after the maximum number e.g. 10 as the minimum number? Or any other codes to fulfil the purpose of my program?
#include<iostream>
using namespace std;
int main() {
int c(0), r(0), n1(0), min(0), max(0), l(0), s(0);
cout << "Please enter the prices: ";
while (n1 != -1) {
cin >> n1;
if (min == 0 && n1>0)
{
min = n1;
}
c++;
if (n1 <= 0 && n1 != -1) { cout << "Invalid. Input again. Please make sure it's a positive number!" << endl; r++; }
else {
if (n1<min && n1 != -1) { min = n1; s++; }
if (n1 >= max && (c - r)>(s + 1)) { max = n1; l = c; }
cout << c << s + 1 << l << endl;
}
}
cout << max << min;
cout << endl << "Largest amount earned: " << (max - min) << endl;
return 0;
}
You can simply calculate maximum profit by using the lowest price from now and not in the future.
#include <iostream>
int main(void) {
int lowestPrice = -1;
int highestProfit = 0;
int price, maxProfit;
while (std::cin >> price) {
if (price < 0) break;
if (lowestPrice < 0 || price < lowestPrice) lowestPrice = price;
maxProfit = price - lowestPrice;
if (maxProfit > highestProfit) highestProfit = maxProfit;
}
std::cout << highestProfit << std::endl;
return 0;
}