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 5 years ago.
Improve this question
/*This code creates two text files : Mokiniai.txt and Vidurkiai.txt
In Mokiniai.txt there are stored each students grades, in Vidurkiai there
should be calculated each students average grade*/
#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int n, k, isvisopazymiu, i, pazymiai;
double vidurkis; //average grade
ofstream myfile;
myfile.open("Mokiniai.txt");
cout << "parasykite kiek mokiniu yra" << endl; cin >> n; //how many students
myfile << n << endl;
cout << "parasykite kiek yra mokiniu pazymiu"; cin >> isvisopazymiu; // how many grades one student has
for (k = 1; k <= n; k++) {
for (i = 1; i <= isvisopazymiu; i++) {
cout << "Parasykite kokie yra mokiniu pazymiai "; cin >> pazymiai; // what are students grades
myfile << " " << pazymiai;
}
myfile << endl;
}
myfile.close();
myfile.open("Vidurkiai.txt"); //trying to calculate average students grades on different file
for (k = 1; k <= n; k++) {
vidurkis = pazymiai / isvisopazymiu; //calculating students grades
myfile << k << " " << vidurkis << endl;
}
myfile.close();
return 0;
}
My problem is that: There is something wrong in vidurkiai.txt file, but I don't know what is wrong.
For example: first students grades are : 7 8 9 7 8, and average grade should be 7,8, but after coding it, in vidurkiai.txt file it shows, that average grade is 1.
The reason why it does not show the grades as expected is because you are not adding up the values.While taking the average over all the grades variable
'pazymiai' stores just the last entered variable. In order to complete the job you can use an 'array' to stores sum of grades in each array element .
cin>>pazymiai;
a[k]+=pazymiai;
where as while calculating grades use
vidurkis = a[k] / isvisopazymiu;
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
im really new to programming and really want some help:). I have made a program that finds the average out of 5 numbers. I was wondering i i could get some help to make this program more efficient. Im using c++.
#include <iostream>
using namespace std;
int main()
{
int num1;
int num2;
int num3;
int num4;
int num5;
int Anum;
int AAnum;
cout << "pick your first number";
cin >> num1;
cout << "pick your second numer";
cin >> num2;
cout << "pick you third number";
cin >> num3;
cout << "pick your forth number";
cin >> num4;
cout << "pick you fifth number";
cin >> num5;
Anum = num1 + num2 + num3 + num4 + num5;
AAnum = Anum / 5;
cout << "the average number is " << AAnum;
return 0;
}
Welcome to programming! How about something like this?
#include <iostream>
using namespace std;
int main() {
double average = 0.0;
const int num_to_average = 5;
for (int i = 0; i < num_to_average; ++i)
{
cout << "Pick number " << i << ": ";
double num;
cin >> num;
average += num;
}
average /= num_to_average;
cout << "the average number is " << average << end;
return 0;
That way the loop does all the heavy lifting for you so instead of 5 separate variables, you can add them all into a single variable (and then computes the average at the end).
Edit: included #tadman's double instead of float suggestion.
The runtime for this program is going to be as good as it's going to get. Each statement will be executed in O(1) time and the runtime performance probably isn't going to improve unless you change the way you prompt for the numbers (i.e. "Enter 5 numbers separated by spaces" and then do cin >> num1 >> num2 >> ...)
Now if you want a better way to write your algorithm, try an array.
At the top:
#define NUMBEROFNUMBERS 5
int inputArray[NUMBEROFNUMBERS];
for(int i = 0; i < NUMBEROFNUMBERS; i++) {
cout << "Pick #" << i + 1 << ": ";
cin >> inputArray[i];
}
And then calculate your average by looping through the array and outputting the result.
It's a short and elegant way to do that if you exactly know the elements of your array.
#include<iostream>
int main()
{
double result = 0;
const double myFirstArray[5] = { 5, 10, 22, 44, 5 };
for (int i = 0; i < std::size(myFirstArray); i++) {
result+=myFirstArray[i];
}
std::cout << "Average: " <<result/ std::size(myFirstArray);
return 0;
}
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 2 years ago.
Improve this question
So basically, I'm new to programming and can't figure it out how to add certain numbers generated by the user. I want a program, capable of collecting for n days the temperature, and at the end, inform what the peak heat occurred, as well as the average of the temperatures collected.
#include <iostream>
using namespace std;
int main()
{
int days, day0 = 0, degrees, degrees_max = 0;
float degrees_average;
cout << "Days of the study" << endl;
cin >> days;
while (days > day0)
{
cout << "How many Degrees?" << endl;
cin >> degrees;
if (degrees < 999)
{
day0++;
}
if (degrees > degrees_max)
{
degrees_max = degrees;
}
}
degrees_average = degrees / days;
cout << "The max temperature was: " << degrees_max << "C"
<< " And the average was : " << degrees_average << endl;
}
SO the only thing left is how to calculate the average.
All the help is appreciated! Thanks
#include <iostream>
using namespace std;
int main()
{
int days, max=-1;
double current, total = 0;
cin >> days;
for (int i=0; i<days; i++){
cin >> current;
if (current > max) max = current;
total = total + current;
}
cout << "max: " << max << endl;
cout << "average: " << total/days << endl;
return 0;
}
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 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 8 years ago.
Improve this question
I am new to C++ and have written some code in which I'm getting the following error:
Run-Time Check Failure #2 - Stack around the variable 'scores' was corrupted
What is causing this error?
Here is my code:
#include <iostream> // Enables cout and endl
#include <string>
#include <sstream>
#include "stdafx.h"
using namespace std;
int getInput();
int main()
{
int scores[5];
int i;
int j;
int numberOfScores;
for (i = 0; i < 6; i++) // Sets all 5 elements of the array to zero
{
scores[i] = 0;
}
cout << "How many scores do you have to enter?\n" << endl;
cin >> numberOfScores;
for (j = 0; j < numberOfScores; j++) // Gather test scores and increases each array index as that score is entered
{
scores[getInput()] ++;
}
cout << "The number of zeros: " << scores[0] << endl;
cout << "The number of ones: " << scores[1] << endl;
cout << "The number of twos: " << scores[2] << endl;
cout << "The number of threes: " << scores[3] << endl;
cout << "The number of fours: " << scores[4] << endl;
cout << "The number of fives: " << scores[5] << endl;
return 0;
}
int getInput()
{
int enteredScore;
cout << "Enter the test scores one at a time.\n";
cout << "The range of scores is 0 to 5.\n";
cin >> enteredScore;
if (enteredScore >= 0 && enteredScore <= 5)
{
return enteredScore;
}
else
{
cout << "Error! The range of scores is 0 to 5.\n";
cout << "Enter the test scores one at a time.\n";
cin >> enteredScore;
return enteredScore;
}
}
It seems that this declaration:
int scores[5];
Is incorrect. This creates an array with 5 numbers in it, indices from scores[0-4], however, you constantly refer to score[5], the sixth element of the array throughout your program. I recommend changing to
int scores[6];
The problem:
You are accessing your array out of bounds in several places.
Here you loop through 6 elements when you only have 5:
for (i = 0; i < 6; i++) // Loops through 6 elements
{
scores[i] = 0;
}
Here you call getInput() and use the return value as the index:
scores[getInput()] ++;
However, the first half of the function accepts inputs from the user in the range 0 to 5, thus allowing access to 6 elements:
if (enteredScore >= 0 && enteredScore <= 5)
It gets even worse if the user enters a number outside that range, as they are then given a second opportunity to enter a number, only this time there is no validation and any number they enter is accepted:
cin >> enteredScore;
return enteredScore;
Finally, you again attempt to access a 6th element here:
cout << "The number of fives: " << scores[5] << endl;
Solution:
First, you need to do one of two things:
Change the for loop, if statement, and cout statements so that they do not access index 5
or:
Create the array so that it has 6 elements: int scores[6];
Secondly, you need to fix the bug in your getInput() function so that it validates the input properly. You could try this for example:
int getInput()
{
int enteredScore;
cout << "Enter the test scores one at a time.\n";
cout << "The range of scores is 0 to 4.\n";
cin >> enteredScore;
while (enteredScore < 0 || enteredScore > 4)
{
cout << "Error! The range of scores is 0 to 4.\n";
cout << "Enter the test scores one at a time.\n";
cin >> enteredScore;
}
return enteredScore;
}
You have an error in
cout << "The number of fives: " << scores[5] << endl;
Your array is of size 5 but you are accessing the 6th element.
Same with for (i = 0; i < 6; i++) should be i < 5.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
So here is my code
#include<iostream>
#include<fstream>
using namespace std;
int main() {
int program = 0;
int score = 0;
cout << "Enter the number of assignments that were graded. " << endl;
cin >> program;
for (int i=1; i <= program; i++)
cout << "Enter the score for assignment #" << i <<": ";
}
Basically I am trying to find a way that would allow the user to input their score along with the cout << Enter the score for assignment #"
Basically I would want the compilier to do this (example):
Enter the number of assignments that were graded: 3
Enter the score for assignment #1: 100
Enter the score for assignment #2: 75
Enter the score for assignment #3: 82
(and so, and so on.)
I really have no idea how I am suppose to put the input along the same loop that I created.
is there anyone that can help me out. what code can I use that would allow unlimited loops of inputs along the same line as Enter the score for assignment #x: (input)
You used incorrect syntax for include directives. Instead of
include iostream
include fstream
there must be
#include <iostream>
#include <fstream>
The program could look the following way
#include <iostream>
#include <vector>
int main()
{
unsigned int program = 0;
std::cout << "Enter the number of assignments that were graded: ";
cin >> program;
std::vector<unsigned int> scores( program );
for ( unsigned int i = 0; i < program; i++ )
{
std::cout << "Enter the score for assignment # " << i + 1 << ':';
std::cin >> scores[i];
}
// ...
Instead of type unsigned int you can use type size_t
Basically, you need to create a block of code in your for loop:
vector<int> grades;
for (int i = 0; i < program; ++i )
{
int temp_grade = 0;
cout << "Enter the score for assignment #" << i <<": "; cin >> temp_grade;
grades.push_back( temp_grade );
}
When you want to use some of the vectors items, you can use either subscripting or iterators.
For printing the grades via iterators:
for(vector<int>::iterator it = grades.cbegin(); it != grades.cend(); ++it)
cout << *it << " ";
I really have no idea how I am suppose to put the input along the same loop
Put another input inside the for loop:
for (int i=1; i <= program; i++) {
cout << "Enter the score for assignment # " << i <<": "<< endl;
int score;
cin >> score;
// ...
}
Writing loops or control flow (if,else) statements like this
for (int i=1; i <= program; i++)
statement();
is dangerous BTW. It's always better to use the braces {}.