Maybe a syntax issue here? - c++

Homework problem I am helping one of my mentees out with (check my history, I have previously asked help with Java in more advanced programs. This is something simple I can't help her figure out). We need to use a while loop to read in numbers, keep track of the count, and keep summing up the numbers entered. We keep getting an error in line 24. Even when I comment it out and run it, the programs doesn't do what it is supposed to do. Been forever since I've done a program in C++ and I need the help of you guys!
#include <iostream>
using namespace std;
int main()
{
int num;
int sum = 0;
int count = 0;
float avg;
cout << "Enter numbers, 999 to quit" << endl;
cin >> num; //
while (num != 999)
{
cout << "Number entered is" << num << endl;
cout << "Enter numbers, 999 to quit" << endl;
cin >> num;
sum = sum + num;
count++;
}
cout << "Total numbers entered: " + count << endl;
cout << "Sum of numbers entered is " + sum << endl;
avg = sum/count;
cout << "Average of numbers entered:" + avg << endl;
return 0;
}

cout << "Total numbers entered: " + count << endl;
cout << "Sum of numbers entered is " + sum << endl;
avg = sum/count;
cout << "Average of numbers entered:" + avg << endl;
Change those +'s to <<'s.
cout << "Total numbers entered: " << count << endl;
cout << "Sum of numbers entered is " << sum << endl;
avg = sum/count;
cout << "Average of numbers entered:" << avg << endl;

#include<iostream>
using namespace std;
int main()
{
int num,count;
float sum,average;
cout << "Enter numbers, 999 to quit" << endl;
cin>>num;
count=0;
sum=0;
while (num!=999)
{
cout<<"Number entered is"<<num<<endl;
++count;
sum+=num;
cout << "Enter numbers, 999 to quit" << endl;
cin>>num;
}
if (count==0) {
count=1;
}// if the first number you enter is 999 count should be 1
// , otherwise avg will be (sum/0 ),which doesn't make sense.
cout << "Total numbers entered: " <<count << endl;
cout << "Sum of numbers entered is " <<sum << endl;
average = sum/count;
cout << "Average of numbers entered:"<<average << endl;
// use << not + because "Total..." is string type and count is int type
system("pause");
return 0;
}
You should pay attention to the type of variable when you do something,which often can cause small errors.

Related

Why does the if statement is always the else part even if the if is true?

I'm having a problem with the if statement at the end.
**if the sum of the cubs of the number a user inputs, is equal to the number itself, say "....". Else, say "....." **
The problem is that it always jumps the if part to the else.
Its a task from the uni, no homework or nothing, just training. IF you have suggestions on how to better I would appreciate that too.
Thank you!
{
int n;
cout << "Write a number different from 0 -> ";
cin >> n;
while (n == 0)
{
cout << "Choose another number -> ";
cin >> n;
}
cout << "Good number " << n << " is!" << "\n";
cout << "lets separate each digit:" << "\n" << " -----------------------------------" << endl;
Sleep(1000);
vector<int> vecN;
while (n != 0)
{
int digit = n % 10;
n /= 10;
cout << n << endl;
cout << "Digit: " << digit << endl;
vecN.push_back(digit);
Sleep(750);
}
cout << "There you go!" << endl;
Sleep(1000);
cout << "Next stage, let's find the cubes for each one of the digits!" << endl;
Sleep(2500);
vector<int> sums;
for (auto i = vecN.begin(); i != vecN.end(); i++)
{
Sleep(500);
int Cubes = pow(*i, 3);
cout << Cubes << endl;
sums.push_back(Cubes);
}
Sleep(1300);
cout << "Now let's sum the cubs and see if the number is an Armstrong Number" << endl;
Sleep(3000);
int armSum = accumulate(sums.begin(), sums.end(), 0);
if ( armSum == n )
{
cout << "Sum: " << armSum << endl;
Sleep(500);
cout << "That's an Armstrong Number!" << "\n"
"The sum of the cubs of each digit in the number is equal to that same number!" << endl;
}
else
{
cout << "Sum: " << armSum << endl;
Sleep(500);
cout << "That's not an Armstrong Number!" << endl;
}
return 0;
} ```
When the if-part is entered, the else-part won't be entered any more. Note that your if/else is not surrounded by a loop. So when control passes by once, e.g. when having entered n==0, then it has passed by and won't step into neither the if nor the else-part a second time.
Try something like
while (n==0) {
cout << "Choose another number -> ";
cin >> n;
}
// continue here; n is != 0

Setting range on a rand using cin integers

I am trying to set the parameters or range for my rands on Friday, Saturday and Sunday so they will only display numbers between minimumSnowfall entered and maximumSnowfall entered. How would one go about doing this? I know how to seed a random number, but have no idea on setting a range. Simple terms if you please(I'm still learning).
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <string>
using namespace std;
int main(void)
{
int minimumSnowfall;
int maximumSnowfall;
char skiResortName[81];
cout << "I will forecast how much snowfall there will be on each \nday this weekend. You get to pick the range. " << endl;
cout << "Please enter the minimum amount of snow that \nwill fall in one day in inches: ";
cin >> minimumSnowfall;
cin.ignore(1, '\n');
cout << "Please enter the maximum amount of snow that \nwill fall in one day in inches: ";
cin >> maximumSnowfall;
cin.ignore(1, '\n');
if (minimumSnowfall < maximumSnowfall)
{
cout << "Enter the name of the ski resort: ";
cin.getline(skiResortName, 81);
cout << "\nThe local forecast for snowfall at " << skiResortName << " this weekend: " << endl;
cout << "Friday: " << rand() % 100 << " inches" << endl;
cout << "Saturday: " << rand() % 100 << " inches" << endl;
cout << "Sunday: " << rand() % 100 << " inches" << endl;
}
else
{
cout << "\nThe maximum snowfall entered is less than the minimum snowfall. " << endl;
cout << "No snowfall reported.\n" << endl;
}
return 0;
}

Float Variable Not Working Inside Switch Statment

So this program is supposed to collect weather temperatures over 7 days using a for loop and then basically just print them back out to the user with an average temperature and the highest recorded temperature. Keep in mind, the following piece of code is a part of a much larger program. Anyway, the problem seems to be the "highest_temp1" float variable. When I run the program it produces some sort of error code instead of the highest temperature. This piece of code was tested in a separate source file and it works no problem.
switch (choice)
{
case 3:
int n;
float temperatures [7];
float lastweektemp [7] = {12.56,8.65,7.5,10,7.9,5,8};
float highest_temp1, highest_temp2;
float accumulated_temp1, accumulated_temp2;
system("CLS");
cout << "____________Weather Data____________" << endl << endl;
for (n = 0; n<7; n++)
{
cout << "What is the temperature for Day " << n+1 << " ?" << endl;
cin >> temperatures[n];
if (highest_temp1 < temperatures [n])
{
highest_temp1 = temperatures [n];
}
if (highest_temp2 < lastweektemp [n])
{
highest_temp2 = lastweektemp [n];
}
accumulated_temp1 = accumulated_temp1 + temperatures[n];
accumulated_temp2 = accumulated_temp2 + lastweektemp [n];
}
cout << endl << " Day This Week Last Week" << endl;
for (n=0; n<7; n++)
{
cout << n+1 << temperatures[n] << lastweektemp[n] << endl;
}
system("CLS");
cout << " Weather Report" << endl;
cout << " --------------" << endl << endl;
cout << "Current Week: " << endl;
cout << "-------------" << endl;
for (n=0; n<7; n++)
{
cout << "Day " << n+1 << ": " << temperatures[n] << endl;
}
cout << endl << " Average: " << accumulated_temp1 / 7 << endl;
cout << " Highest Temperature: " << highest_temp1 << endl;
cout << "Last Week: " << endl;
cout << "----------" << endl;
for (n=0; n<7; n++)
{
cout << "Day " << n+1 << ": " << lastweektemp[n] << endl;
}
cout << endl << " Average: " << accumulated_temp2 / 7 << endl;
cout << " Highest Temperature: " << highest_temp2 << endl;
system("PAUSE");
}
The highest temperature in current week is 24 but it is printing "Highest Temperature: 3.45857e+032"
This exact 'error-code' is appearing every time I run the program it doesn't change.
I am a newbie hence why I can't upload a photo.
Any help would be appreciated. I'm doing a small assignment in college. This is my first question so go easy !!
You have not assigned any value to teh variable highest_temp1 and you are comparing it with another value.
Basically you will need to assign it a value first before you compare..
highest_temp1 = 10.00
(or anything that it is supposed to contain)
You have not initialised highest_temp1 (or highest_temp1 for that matter: after that I stopped looking).
Same for accumulated_temp, which gets not initialised. can be done via
float accumulated_temp1(0);
Initialize variables before using them
float highest_temp1(-FLT_MAX); // -FLT_MAX insures results of first compare
float highest_temp2(-FLT_MAX); // Could use -1.0/0.0 of -INFINITY instead
float accumulated_temp1(0.0);
float accumulated_temp2(0.0);
For float number condition use if statements switch is not able to work in case of float number, switch only work for integer number.

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) { ... }

C++ Factor Program: Outputting Number of Factors Given

I am writing a simple program that finds the factors of a list of integers through Linux Redirection. I am almost done, but I am stuck on one part. Here is my program so far:
#include<iostream>
using namespace std;
int main()
{
int counter = 0;
int factor;
cin >> factor;
while (cin)
{
if (factor < 0)
break;
cout << "The factors of " << factor << " are " << endl;
for(int i=factor; i>=1; i--)
if (factor % i == 0)
{
counter++;
cout << i << endl;
}
cout << "There are " << " factors." << endl;
cout << endl;
cin >> factor;
}
return 0;
}
Now the problem I have is in the line " cout << "There are " << " factors." << endl; ". I'm not sure how to calculate the number of factors output by the program.
For example:
The factors of 7 are
1
7
There are 2 factors.
How would I go about calculating and outputting the "2" in this example.
Help is greatly appreciated.
Instead of
cout << "There are " << " factors." << endl;
use
cout << "There are " << counter << " factors." << endl;
If you do that, you have to move the line where you define counter.
Instead of it being the first line in main, it needs to be moved to be the first line in the while loop.