#include <iostream>
using namespace std;
// on input n returns the value a_n as a double
double term(int n) {
double val = 1.0 / (n+1.0) / (n+1.0);
if (n%2 != 0) val = -val;
return val;
}
/* computes the sum for i from k to k+n-1 of term(i) by the
* direct upwards method */
double direct_up(int k,int n) {
double sum = 0.0;
for (int i=0; i<n; i++) {
sum += term(k+i);
}
return sum;
}
int main() {
cout.precision(16);
int nterms = 0;
int ft = 0;
cout << "Enter first term, number of terms" << endl;
cin >> ft >> nterms;
cout << "The sum of the " << nterms << " terms starting at " << ft << endl;
cout << "direct_up: " << direct_up(ft, nterms) << endl;
return 0;
}
I have created a program which takes a formula and adds term by term starting from the kth term to the (n-1)th term. However I am unable to work out how to calculate the roundoff error after each term?
Would you be able help me with this please?
Related
I want to find Maximum numbers from my "numbers.txt" file and amount of negative numbers. And i want to output the Total result to another .txt file and console and the rest to the console only.
Im very new and just cant figure out how to do it.
This is what i have now
a "numbers.txt" file with
-4
53
-5
-3
2
and
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int n = 0;
int sum = 0, total = 0;
fstream file("numbers.txt");
while (file >> n)
{
sum += n;
total++;
}
int average = (float)sum / total;
int AmountOfNumbersAdded = total;
int Highest;
int Negative;
cout << "Total result: " << sum << endl;
cout << "Numbers added: " << AmountOfNumbersAdded << endl;
cout << "Average number: " << average << endl;
cout << "Maxiumum number: " << endl;
cout << "Negative numbers: " << endl;
return 0;
}
i tried to do
float Highest = INT_MIN;
if (Highest < num[i]) {
Highest = num[i];
but it just wouldn't work.
You don't need to store the numbers to find the maximum or the amount of negative numbers, but you need to track them inside the loop, like you're already doing with the sum and the total amount of numbers.
int Highest = INT_MIN;
int Negative = 0;
while (file >> n)
{
sum += n;
total += 1;
if (n < 0)
{
Negative += 1;
}
if (n > Highest)
{
Highest = n;
}
}
float average = (float)sum / total;
Here's what you're looking for.
#include <iostream>
#include <fstream>
int main()
{
int n = 0;
int sum = 0, total = 0;
int highest = 0;
int negatives = 0;
std::fstream file("numbers.txt");
while (file >> n)
{
if (n > highest) highest = n;
if (n < 0) ++negatives;
sum += n;
++total;
}
int average = (float)sum / total;
int AmountOfNumbersAdded = total;
std::cout << "Total result: " << sum << "\n";
std::cout << "Numbers added: " << AmountOfNumbersAdded << "\n";
std::cout << "Average number: " << average << "\n";
std::cout << "Maxiumum number: " << highest << "\n";
std::cout << "Negative numbers: " << negatives << "\n";
file.close();
return 0;
}
As you're new, few advices for you:
Never use using namespace std.
Prefer using "\n" instead of std::endl.
Don't forget to close any files/database after opening them like you did in your code.
Always try to avoid macros.
For my class, I am needing to write a program using arrays instead of individual variables that contain the score. Struggling with this chapter. I'll leave my code below. Any help would be greatly appreciated. Needing to find the sum between all of the scores entered, subtract the highest and lowest and then find the average.
#include <iostream>
#include <iomanip>
using namespace std;
// Function prototypes
void getJudgeData(double, double);
double calcScore(double);
double findLowest(double);
double findHighest(double);
int main()
{
// Declare variables
const int SIZE = 7;
double scores[SIZE];
double sum;
for (int x = 0; x < SIZE; x++)
double getJudgeData(scores[x]);
return 0;
}
// Function getJudgeData
void getJudgeData(double &judgeScore, double scores[])
{
static int judge = 1;
cout << "Enter score " << judge << ": ";
cin >> judgeScore;
while (judgeScore < 0 || judgeScore > 10)
{
cout << "Invalid score, please enter a score between 0 and 10";
cout << "Enter score " << judge << ": ";
cin >> judgeScore;
}
judge++;
return;
}
// Function calcScore
double calcScore(double scores[])
{
double highest = findHighest(scores);
double lowest = findLowest(scores);
double result = 0;
for (int x = 0; x < 7; x++)
{
result += scores[x];
}
result - findHighest(scores) - findLowest(scores);
cout << fixed << showpoint << setprecision(2);
cout << "The average after the dropping the highest and lowest scores: " << result / 5 << endl;
return result;
}
// Function findLowest
double findLowest(double scores[])
{
double result = 10;
for (int x = 0; x < 7; x++)
{
if (scores[x] < result)
result = scores[x];
}
return result;
}
// Function findHighest
double findHighest(double scores[])
{
double result = 0;
for (int x = 0; x < 7; x++)
{
if (scores[x] > result)
result = scores[x];
}
return result;
}
I created a program to display an average from an array of numbers the user have decided to input. The program asks the user the amount of numbers he / she will input, then they input all positive numbers. The output for the average is always a decimal, how can I only display the whole number without any decimal points. Ex. 12.34 = 12 / 8.98 = 8
#include <iostream>
#include <iomanip>
using namespace std;
void sortingTheScores(double *, int);
void showsTheScoresNumber(double *, int);
double averageForAllScores(double, int);
int main()
{
double *scores;
double total = 0.0;
double average;
int numberOfTestScores;
cout << "How many test scores do you have? ";
cin >> numberOfTestScores;
scores = new double[numberOfTestScores];
if (scores == NULL)
return 0;
for (int count = 0; count < numberOfTestScores; )
{
cout << "Test Score #" << (count + 1) << ": ";
cin >> scores[count];
while (scores[count] <= 0)
{
cout << "Value must be one or greater: " ;
cin >> scores[count];
}
count = count +1;
}
for (int count = 0; count < numberOfTestScores; count++)
{
total += scores[count];
}
sortingTheScores(scores, numberOfTestScores);
cout << "The numbers in set are: \n";
showsTheScoresNumber(scores, numberOfTestScores);
averageForAllScores(total, numberOfTestScores);
cout << fixed << showpoint << setprecision(2);
cout << "Average Score: " << averageForAllScores(total,numberOfTestScores);
return 0;
}
void sortingTheScores (double *array, int size)
{
int sorting;
int theIndex;
double theNumbers;
for (sorting = 0; sorting < (size - 1); sorting++)
{
theIndex = sorting;
theNumbers = array[sorting];
for (int index = sorting + 1; index < size; index++)
{
if (array[index] < theNumbers)
{
theNumbers = array[index];
theIndex = index;
}
}
array[theIndex] = array[sorting];
array[sorting] = theNumbers;
}
}
void showsTheScoresNumber (double *array, int size)
{
for (int count = 0; count < size; count++)
cout << array[count] << " ";
cout << endl;
}
double averageForAllScores(double total, int numberOfTestScores)
{ double average;
average = total / numberOfTestScores;
return average;
}
You can use I/O manipulators here:
#include <iostream>
#include <iomanip>
int main()
{
std::cout << std::setprecision(0) << 1.231321 << '\n';
}
Output:
1
You can do it without using iomanip library:
std::cout.precision(0);
std::cout << 1.231321 << std::endl;
Then you'll simply get:
1
Just you need to use std::cout.precision() which is equivalent to std::setprecision() from iomanip library.
Edit:
The aforementioned solution is okay for smaller floating point values, but if you try something like 1334.231321, the std::cout will result displaying some scientific notation, something like:
1e+03
which is actually odd to read and understand. To solve it, you need std::fixed flag, you may write something like:
std::cout.precision(0), std::cout << std::fixed;
std::cout << 1334.231321 << std::endl;
Then it'll show:
1334
For numbers in a +/-2^31 range you can do:
cout << int(12.34) << " " << int(8.98) << endl;
which produces output
12 8
You may also want to consider rounding to the nearest integers. To do so
add a line
#include <cmath>
then do
cout << int(rint(12.34)) << " " << int(rint(8.98)) << endl;
this gives
12 9
Compile and run my code; compare the result if you are using integers or floats with fractional values. Why is there a difference?
Here is my code:
#include <iostream>
using namespace std;
template<class T>
T find(T array[], T len, T num){
for (int i = 0; i < len; ++i){
if (array[i] == num)
return i;
}
return -1;
}
int main () {
int array1[5] = { 4, 7, 3, 5, 6 }, num1;
float array2[5] ={121.2, 111.5, 300.1, 500.1, 600.1 }, num2;
cout << "Enter an int:" << " " ;
cin >> num1;
cout << "Enter a float:" << " " ;
cin >> num2;
int x = find<int>(array1,5,num1);
float y= find<float>(array2,5,num2);
cout << "The index for the int is:" << " " << x << endl;
cout << "The index for the float is:" << " " << y << endl;
return 0;
}
I couldn't find the difference between the two results when using ints and when using floats.
The issue is that you must not compare floats with == due to the internal representation of floating point numbers. If you are using the result from an expression, it can mathematically be correct to find the number in the array, but due to the limitations in the floating point representation the == would not find it.
Consider the following code:
template<class T>
int find(T array[], size_t len, T num){
for (size_t i = 0; i < len; ++i){
cerr << std::setprecision(7) << "Compare: " << array[i] << ", " << num;
if (array[i] == num) {
cerr << " => equal" << endl;
return i;
} else {
cerr << " =>not equal" << endl;
}
}
return -1;
}
int main () {
float array2[2] ={500.1, 1.0 }, num2;
float a = 500.1 / 2;
int i = find<float>(array2, 2, 2*a);
a = 1.0 / 0.3333;
i = find<float>(array2, 2, a * 0.3333);
return 0;
}
Output:
Compare: 500.1, 500.1 => equal
Compare: 500.1, 0.9999999 =>not equal
Compare: 1, 0.9999999 =>not equal
So, even though 1.0 / 0.3333 * 0.3333 is 1.0 mathematically, it is not when using floating point arithmetics - it is 0.99999 instead. Therefore == does not treat the numbers as equal in the last comparison.
To solve this, compare the difference of the two numbers to a small epsilon value. float.h explicitly defines the constant FLT_EPSILON for this:
if (fabs(array[i] - num) < FLT_EPSILON) { ...
I am currently doing a task in a book which asks me to calculate the mathematical constant e using the while loop. I managed that fairly easily, however I am having troubles calculating e^x, whereas the user inputs x and the degree of accuracy. The code I used for computing e is:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int degreeOfAccuracy, x = 1;
long double e = 1;
cout << "Enter degree of accuracy of mathimatical constant e: ";
cin >> degreeOfAccuracy;
while (x <= degreeOfAccuracy)
{
int conter = x;
int intial = x;
long double number = x;
int counter = 1;
while (conter > 1)
{
number = number*(intial-counter);
counter++;
conter--;
}
e += (1/number);
x++;
}
cout << endl << "The mathematical constantr e is: "
<< setprecision(degreeOfAccuracy) << fixed << e << endl;
system("pause");
return 0;
}
However, when I tried e^x the following code returned a completely wrong value:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int degreeOfAccuracy, x = 1, exponent;
long double e = 1;
cout << "Enter degree of accuracy of mathimatical constant e: ";
cin >> degreeOfAccuracy;
cout << "Enter the number of which you wish to raise to e: ";
cin >> exponent;
int temp = exponent;
while (x <= degreeOfAccuracy)
{
exponent = temp;
int conter = x;
int intial = x;
long double number = x;
int counter = 1;
while (conter > 1)
{
number = number*(intial-counter);
counter++;
conter--;
}
int counterr = 1;
while (counterr < x)
{
exponent *= exponent;
counterr++;
}
e += (exponent/number);
x++;
}
cout << endl << "The mathematical constantr e is: " << setprecision(degreeOfAccuracy) << fixed << e << endl;
system("pause");
return 0;
}
Any ideas where the calculations went wrong?
This line:
exponent *= exponent;
is wrong. It should be:
exponent *= temp;