Cumulative sum with array in C++ - c++

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <cmath>
#include <fstream>
#include <iomanip>
#include <sstream>
using namespace std;
int iData, tData;
void randgen(int max, int min){
srand((unsigned) time(0));
}
int main()
{
cout << "Masukkan jumlah data: ";
cin >> iData;
int jData[iData], randNum[iData], fProb[iData];
double probkei[iData], tKumul[iData],tepiA[iData], tepiB[iData];
int tData;
for(int i=1; i<=iData; i++){
cout << "Masukkan data ke-" << i << ": ";
cin >> jData[i];
tData += jData[i]; //jumlahkan seluruh data untuk mencari probabilitas tiap variabel
}system("cls");
probkei[0]=0;
cout << setw(10) << "Data ke" << setw(10) << "Frekuensi" << setw(15) << "Probabilitas" << setw(20) << "Kumulatif" << setw(10) << "Interval" << endl;
for(int i=0; i<iData; i++){
probkei[i] = (double) jData[i]/tData; //typecast integer to double for the probability
if(jData[i]==jData[1]){
tKumul[i] = probkei[i];
}else if(i<i+i){
tKumul[i] = probkei[i] + probkei[i+1]; //for cumulative sum 1 way
}
probkei[i] = round(probkei[i] * 1000.0) / 1000.0; //rounding the probability
tKumul[i] = round(tKumul[i] * 1000.0) / 1000.0;
cout << setw(10) << i+1 << setw(10) << jData[i] << setw(15) << probkei[i] << setw(20);
int temp;
cout<<"data "<<probkei[i]+probkei[i+1]; //for cumulative sum 2 way
cout << setw(10) << tKumul[i] << endl;
/*if (i == iData || jData[i] != jData[i - 1])
{
temp += count;
cout << "Cumulative frequency of " << jData[i - 1] << " in the array is: " << temp << endl;
count = 1;
}else{
count++;
}*/
}
cout << setw(20) << "Total data: " << tData << endl;
return 0;
}
I want to count cumulative frequency from my array data.
First is entering the value/total of the number of data in the array. Next is entering the value for each data one by one and then counting all probabilities of each data(the possibilities are declared in double). And then counting the cumulative which is sum the n data with the n+1 data. And the last is making the top and bottom edges for each data to be used as a random number interval.
I've done my best and finding the solution but I still confused why it's doesn't work.
I was trying to count it in 2 ways but all of them do nothing.
This is a Monte Carlo Simulation.
example Table

This:
int iData;
cin >> iData;
int jData[iData];
is using variable-length arrays, which are not standard C++. Rather use std::vector instead:
int iData;
cin >> iData;
std::vector<int> jData(iData);
The tData local variable is uninitialized:
int tData;
...
tData += jData[i];
It should be initialized to 0.
The condition i<i+i doesn't make sense.
There is something weird going on with the indexes. The input is loaded from index 1 but the second loop starts from 0. This loading from 1 is also not accounted in size of the arrays, so the last element will overflow the array.
There is something wrong with this too:
tKumul[i] = probkei[i] + probkei[i+1];
If this is supposed to be cumulative sum then tKumul should appear on the right side too.
If we load data from 0, then the second loop should look like this:
for (int i = 0; i < iData; i++) {
probkei[i] = (double) jData[i] / tData;
if (i == 0) {
tKumul[i] = probkei[i];
} else {
tKumul[i] = probkei[i] + tKumul[i-1];
}
With this code (see godbolt) the output is:
Data ke Frekuensi Probabilitas Kumulatif
1 5 0.067 0.067
2 10 0.133 0.2
3 15 0.2 0.4
4 20 0.267 0.667
5 25 0.333 1
Total data: 75
In addition I would suggest using fixed and setprecision(3) instead of manual rounding:
cout << fixed << setprecision(3);
and using algorithms instead of loops. Calculating probabilities can be replaced by std::transform and calculating cumulative sum can be replaced by std::partial_sum:
std::transform(
jData.begin(), jData.end(),
probkei.begin(),
[tData](auto elem) { return (double) elem / tData; }
);
std::partial_sum(probkei.begin(), probkei.end(), tKumul.begin());
With this code (see godbolt) the output is:
Data ke Frekuensi Probabilitas Kumulatif
1 5 0.067 0.067
2 10 0.133 0.200
3 15 0.200 0.400
4 20 0.267 0.667
5 25 0.333 1.000
Total data: 75

Related

Accessing the value of the last iteration from inside the loop

I know this might be just an if statement that i don't know where to place but i am having difficulties understanding how to proceed.
#include <time.h>
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
float a;
float sum;
float tA = 5050 ;
int b [5] = {5, 10, 15, 30, 100};
double bin;
double divident;
cout<<"Random numbers generated between 0 and 1:"<<endl;
srand( (unsigned)time( NULL ) );
for (int i = 0; i < 5; i++)
{
a = (float) rand()/RAND_MAX;
sum += a;
cout << a << "\t Total: " << sum << "\t Bin: " << a* divident << endl;
}
cout << "Total of Random Numbers: " << sum << endl;
divident = tA/sum;
cout <<"Divident: "<< divident << endl;
cout <<"Last a: "<< a << endl;
return 0;
}
OUTPUT:
Random numbers generated between 0 and 1:
0.228659 Total: 0.228659 Bin: 0
0.337218 Total: 0.565877 Bin: 0
0.955376 Total: 1.52125 Bin: 0
0.356451 Total: 1.8777 Bin: 0
0.7963 Total: 2.674 Bin: 0
Total of Random Numbers: 2.674
Divident: 1888.55
Last a: 0.7963
The dividend should be a variable (tA)/the sum of all 5 random generated numbers (2.674) and every random value of 'a' be multiplied by it on every row (inside bin column). But I do not know exactly how to access it since in the code it is the last iteration of 'sum'
as you can see my next step is to place all five values into a designated array bin *int b[5](labeled 5, 10, 15, 30, 100). and eventually multiply the expected frequency in every bin with the bin label(5,10,15.. 1000) I'm thinking std map or something similar, so any advanced std solutions or pointers (sic) on how to proceed further would greatly be appreciated.
You can only compute divident after the end of the loop, but you want to use it starting with the first iteration: that is not possible using one single loop. You should use two loops, first one to compute sum and divident, and second one to display the values:
float sum = 0;
...
double arr[5];
for (int i = 0; i < 5; i++)
{
a = (float)rand() / RAND_MAX;
sum += a;
arr[i] = a;
}
divident = tA / sum;
for (int i = 0; i < 5; i++)
{
a = arr[i];
cout << a << "\t Total: " << sum << "\t Bin: " << a * divident << endl;
}

Beginner to C++ - How to sum up only positive or only negative integers the user inputs and how to calculate the avg

Total Noob here, I am having a hard time with an assignment. I am taking a beginner course in C++ and have to figure out how to calculate the sum of negative integers and their avg. Sum of positive integers and the avg. And the sum of all numbers and the avg. I have gotten the last part already but how do I calculate the sum of negative integers and avg, and positive integers and avg using a while loop?
I provided my code below.
#include <iostream>
using namespace std;
#include <iomanip>
int main(int argc, const char * argv[]) {
int x;
double avg = 0.0;
int count = 0;
int sum = 0;
// ask users for input
cout << ("Welcome to the greatest calculator!\n");
cout << ("Please enter 10 integers seperated by spaces \n");
do {
std::cin >> x;
sum = sum + x;
count = count + 1;
}
while (count < 10);
// calculate average
avg = sum/10.0;
// output average
cout << fixed;
cout << "For all 10 numbers the sum is " << sum << "." "The average is " << setprecision (2) << sum/10.0 <<".\n";
return 0;
}
The output should look something like this.
Please enter 10 integers separated by spaces:
1 -1 45 17 28 -2 0 9 -14 11
Upon our intelligent calculations, here is the result:
+ There are 7 positive numbers, sum = 111.00 and average = 15.86
+ There are 3 negative numbers, sum = -17.00 and average = -5.67
+ For all 10 numbers, sum = 94.00 and average = 9.40 */
Use two variable int negativeVar=0 , PositiveVar=0 . In the loop try a condition if(GivenNumber<0) to detect the given number is negative or positive. Then add all positive and negative value separately and make avarage.
(Sorry for bad english)
You can do like this (notice comments):
#include <iostream>
int main(void) {
// Declaration and initialization of the required variables
float cPositive = 0.0f;
float cNegative = 0.0f;
int it = 0;
std::cout << "Enter 10 numbers (floating point assignable): \n";
// Looping till 10 iterations
do {
float temp;
std::cin >> temp;
// If the number is greater than zero, i.e. (+ve) then cPositive sums up
// otherwise, cNegative
if (temp > 0) cPositive += temp;
else if (temp <= 0.0f) cNegative -= temp;
} while (++it < 10); // Increment and comparison together
// Final results
std::cout \
<< "Sum of positive: " << cPositive << std::endl
<< "Sum of negative: -" << cNegative << std::endl;
return 0;
}
A simple test case:
Enter 10 numbers (floating point assignable):
10.5
-1.5
2.2
5.5
-3.8
-99.3
10
4.5
-1.0
0
Sum of positive: 32.7
Sum of negative: -105.6
Moreover, if you want to see average, then declare two variables, pos and neg where both are initially zero. After that, when a positive number or negative number occurs, just increment pos or neg and divide with them by cPositive or cNegative respectively.
#include <iostream>
#include <string>
using namespace std;
int main()
{
// lets declare some variable first.
int positiveSum =0; //this will hold sum of positive nums
int negativeSum =0; // this will hold sum of negative nums
int totalSum =0; // this will hold sum of all the nums
int number=0; // user input for number
for (int i = 1; i <=10; i++) // loop from 1 to 10 times
{
cout << " Enter a number: ";
cin >> number;
// now check if number is positive or negative
if (number >=0)
{
positiveSum += number; // adds this number to positiveSum
}
else if (number < 0)
{
negativeSum += number; // adds this number to negativeSum
}
}
// So finally add the positiveSum and negativeSum to get the totalSum
totalSum = positiveSum + negativeSum;
cout << endl;
cout << " Total of Positive numbers is: " << positiveSum << endl;
cout << " Total of Negative numbers is: " << negativeSum << endl;
cout << " Total of all numbers is: " << totalSum << endl;
return 0;
}
The code below produces the following output:
$ ./main
The (sum, avg) of negative integers = (-15, -5)
The (sum, avg) of positive integers = (6, 2)
The (sum, avg) of all numbers = (-9, -1.5)
Please read the comments because they are in fact the detailed answer.
#include <array>
#include <iostream>
int main()
{
// For convenience, keep the numbers in an std::array. std::vector is
// equally convenient.
std::array<int, 6> integers { 1, -4, 2, -5, 3, -6 };
// Define variables that store the sums and the counts.
int positiveSum = 0;
int positiveCnt = 0;
int negativeSum = 0;
int negativeCnt = 0;
// Iterate over the numbers taking one of them at a time.
int i = 0;
while (i < integers.size())
{
int number = integers[i];
// Is the number positive?...
if (number >= 0)
{
// ... it is - add it to the positive sum and increment the count.
positiveSum += number;
++positiveCnt;
}
// The number is not positive, so it must be negative...
else
{
// ... add it to the negative sum and increment the count.
negativeSum += number;
++negativeCnt;
}
// Get ready for the next number.
++i;
}
// Time to print out the results.
// Note that before we calculate the average, we have to cast at least one
// of the terms of the division to floating point type. Otherwise the
// division will be done with integers where the result is also an integer
// (e.g. 3 / 2 -> 1).
// Only affter the casting you will be getting expected answers
// (e.g. double(3) / 2 -> 1.5).
std::cout <<
"The (sum, avg) of negative integers = (" <<
negativeSum << ", " <<
double(negativeSum) / negativeCnt << ")" << std::endl;
std::cout <<
"The (sum, avg) of positive integers = (" <<
positiveSum << ", " <<
double(positiveSum) / positiveCnt << ")" << std::endl;
std::cout <<
"The (sum, avg) of all numbers = (" <<
negativeSum + positiveSum << ", " <<
double(negativeSum + positiveSum) / (negativeCnt + positiveCnt) << ")" << std::endl;
}
#include <iostream>
using namespace std;
int main()
{
char op;
float num1,num2;
cout << "Enter two operands: ";
cin >> num1 >> num2;
switch(op)
{
case '+':
cout << num1+num2;
break;
case '-':
cout << num1-num2;
break;
case '*':
cout << num1*num2;
break;
case '/':
cout << num1/num2;
break;
default:
//If the operator is other than +,-,*,/, error message is shown.
cout << "Error! operator is not correct";
break;
}
return 0;
}

How to display whole numbers without decimals

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

Estimating Pi with the Monte Carlo method, loop appears to be terminating early

I am attempting to write a program that estimates Pi based on the Monte Carlo method via a random number generator. I am attempting to estimate Pi within 1, 2, 3, 4, 5, and 6 digits of accuracy and have the program print to the screen how many points it took to get within .1 digit of Pi, then .01 digits of Pi and so forth all the way until .000001 digits of Pi. I am allowing the user to input an amount of trials they would like to run, so it will print "Trial 1, 2, 3, 4" etc. with all of the information I listed above. I am stuck on one last bit, and that is having it loop back through the calculations (it will not print more than just trial 1). Though I am not getting a message that the program has terminated, so I can not tell if it is my while loop failing or my nested for loops. Please help! :)
I have attempted switching around the for loops as well as trying different varying if statements. This is the closest I have gotten it to running the way I would like with exception of allowing the user to run multiple trials.
#include "pch.h"
#include <iostream> //need this by default for cin
#include <math.h> //includes math functions
#include <cmath> //includes basic math
#include <cfloat> //includes floating point numbers
#include <iomanip> //includes setprecision for decimal places
#include <cstdlib> //needed for rand and srand functions
#include <ctime> //needed for time function used to seed generator
using namespace std;
int main()
{
cout << "The purpose of this program is to estimate pi using the monte
carlo method and a random number generator" << endl << endl;
unsigned seed = time(0);
srand(seed);
float radius;
int trialcount = 0;
int trials;
float accuracy;
const float pi = 3.14159265;
float randpi = 0;
int squarecount = 0;
int circlecount = 0;
float x;
float y;
int n;
cout << "The value of PI can be found as the ratio of areas of a circle of radius r located within a square of side 2r" << endl;
cout << "This program runs a MonteCarlo Simulation that generates numbers located randomly within a square" << endl;
cout << "The count of values within the square and the count of numbers within the circle approximate their areas" << endl;
cout << "An input value of radius determines the size of the circle and square" << endl;
cout << "The user specifies how many trials or test runs are desired" << endl << endl;
cout << "The true value of PI to 8 decimal places is 3.14159265" << endl << endl;
cout << "Input a value for radius: ";
cin >> radius;
cout << endl;
cout << "How many trials would you like? ";
cin >> trials;
cout << endl << endl;
cout << "Square count gives the Total number of random samples (they are within the square)" << endl;
cout << "Circle count gives the number of random samples that also fall within the circle" << endl << endl;
while (trialcount != trials)
{
accuracy = .1;
cout << "Trial " << trialcount + 1 << endl;
cout << "Accuracy \t\t" << "Square Count \t\t" << "Circle Count \t\t" << "Pi" << endl << endl;
for (int j = 0; randpi >= pi - accuracy || randpi <= pi + accuracy; j++)
{
cout << setprecision(6) << fixed << accuracy << " \t\t" << squarecount << " \t\t" << circlecount << " \t\t" << randpi << endl << endl;
accuracy = accuracy / 10;
for (int i = 0; randpi >= pi + accuracy || randpi <= pi - accuracy; i++)
{
x = (float)(rand());
x = (x / 32767) * radius;
y = (float)(rand());
y = (y / 32767) * radius;
squarecount++;
if ((x * x) + (y * y) <= (radius * radius))
{
circlecount++;
}
randpi = float(4 * circlecount) / squarecount;
}
}
trialcount++;
}
}
Problems I see:
Problem 1
The first for loop does not make any sense. If you want to make sure that you use accuracies of 0.1, 0.01, 0.001, etc. you just need a simple for loop. The following should do:
for ( int j = 0; j < 6; ++j )
{
...
}
Problem 2
x and y values are computed incorrectly. You want to make sure that their values are less than or equal to radius. However, when you use:
x = (float)(rand());
x = (x / 32767) * radius;
y = (float)(rand());
y = (y / 32767) * radius;
they are not guaranteed to be less than or equal to radius. They will be more than radius more often than they will not. You need to use
x = (float)(rand() % 32768);
x = (x / 32767) * radius;
y = (float)(rand() % 32768);
y = (y / 32767) * radius;
Problem 3
You need to reset the values of randpi, squarecount, and circlecount in every iteration of the inner for loop. Otherwise, your computations will be affected by computations from the previous iteration.
The outer for loop must start with:
for (int j = 0; j < 6; j++)
{
accuracy /= 10;
randpi = 0;
squarecount = 0;
circlecount = 0;
Problem 4
The inner for loop must be constrained to only run upto a certain number of times. If for some reason the accuracy is not achieved, you want to make sure you don't overflow i. For example:
int stopAt = (INT_MAX >> 8);
for (int i = 0; (randpi >= pi + accuracy || randpi <= pi - accuracy) && i < stopAt; i++)
For machines that use 32 bit ints, which is the most common in practice today, you won't run the loop any more than 0x7FFFFF (8388607 in decimal) times.
This is the core problem in your code. Your computations don't converge some times and you don't make sure you exit after a certain number of iterations of the loop.
Further improvement
You don't need radius as a variable in your program. You can compute x and y as:
x = (float)(rand() % 32768);
x = (x / 32767);
y = (float)(rand() % 32768);
y = (y / 32767);
and change the logic to check whether this is a point within the circle to
if ((x * x) + (y * y) <= 1.0 )
You should also attempt to define variables only in the scopes where you need them. This will make sure that you don't end up using stale values from a previous run of the iteration.
Revised program
The following revised program works for me.
#include <iostream> //need this by default for cin
#include <math.h> //includes math functions
#include <cmath> //includes basic math
#include <cfloat> //includes floating point numbers
#include <iomanip> //includes setprecision for decimal places
#include <cstdlib> //needed for rand and srand functions
#include <ctime> //needed for time function used to seed generator
#include <climits>
using namespace std;
int main()
{
cout << "The purpose of this program is to estimate pi using the monte "
"carlo method and a random number generator" << endl << endl;
unsigned seed = time(0);
srand(seed);
int trialcount = 0;
int trials;
float accuracy;
const float pi = 3.14159265;
cout << "The value of PI can be found as the ratio of areas of a circle of radius r located within a square of side 2r" << endl;
cout << "This program runs a MonteCarlo Simulation that generates numbers located randomly within a square" << endl;
cout << "The count of values within the square and the count of numbers within the circle approximate their areas" << endl;
cout << "An input value of radius determines the size of the circle and square" << endl;
cout << "The user specifies how many trials or test runs are desired" << endl << endl;
cout << "The true value of PI to 8 decimal places is 3.14159265" << endl << endl;
cout << endl;
cout << "How many trials would you like? ";
cin >> trials;
cout << endl << endl;
cout << "Square count gives the Total number of random samples (they are within the square)" << endl;
cout << "Circle count gives the number of random samples that also fall within the circle" << endl << endl;
while (trialcount != trials)
{
accuracy = 0.1;
cout << "Trial " << trialcount + 1 << endl;
cout << "Accuracy \t\t" << "Square Count \t\t" << "Circle Count \t\t" << "Pi" << endl << endl;
for (int j = 0; j < 6; j++)
{
accuracy /= 10;
float randpi = 0;
int squarecount = 0;
int circlecount = 0;
int stopAt = (INT_MAX >> 8);
for (int i = 0; (randpi >= pi + accuracy || randpi <= pi - accuracy) && i < stopAt; i++)
{
float x = ((float)(rand() % 32768) / 32767);
float y = ((float)(rand() % 32768) / 32767);
squarecount++;
if ((x * x) + (y * y) <= 1.0 )
{
circlecount++;
}
randpi = float(4 * circlecount) / squarecount;
}
cout << setprecision(8) << fixed << accuracy << " \t\t" << squarecount << " \t\t" << circlecount << " \t\t" << randpi << endl << endl;
}
trialcount++;
}
}
See it working at https://ideone.com/laF27X.

Temperature table using for loop c++ [closed]

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
Super new to coding and I've been stuck for awhile on this question. I need to make a program that inputs the temperature in Celsius and an increment that is inputted for a total of 20 lines. In the process it converts to Fahrenheit, Kelvin, and Rankine. That is all fine but I can't get the values to increment by my input.
e.g., As it should look:
Enter temperature in Cel: 50
Enter increment: 5
Cel Far Kel Rank
1 - 50 ...............................
2 - 55 ..............................
3 - 60 ..............................
.
.
.
.
20 - 150 .............................
I can't get the values to increment at all. Being reading my notes and looking online to understand the issue but no luck.
#include <iostream>
#include <math.h>
#include <iomanip>
using namespace std;
int main()
{
int CELS; // celsius entry
int x; // x = input value for increment
double FAH = (CELS * (9.0 / 5) + 32); // farenheit conversion
double KEL = (CELS + 273.15); // kelvin conversion
double RANK = ((CELS + 273.15) * (9.0 / 5)); // rankine conversion
cout << "Enter the temperature in celsius: ";
cin >> CELS;
while ((CELS < -273.15) || (CELS > 5000))
{
cout << "ERROR: out of range." << endl;
cout << "Enter the temperature in celsius: ";
cin >> CELS;
}
cout << "Enter the increment value: ";
cin >> x;
cout << endl;
cout << " # Cels Fahr Kel Rank" << endl;
cout << right;
for (int i = 1; i <= 20; i++)
{ //
for (double j = CELS; j <= CELS; x++)
{ //
for (double k = (CELS * (9.0 / 5) + 32);
k <= (CELS * (9.0 / 5) + 32); x++)
{
for (double m = (CELS + 273.15); m <= (CELS + 273.15); x++)
{
for (double n = ((CELS + 273.15) * (9.0 / 5));
n <= ((CELS + 273.15) * (9.0 / 5)); x++)
{
cout << setw(10) << i << setw(10) << j << setw(10) << k
<< setw(10) << m << setw(10) << n << endl;
}
}
}
}
}
}
And ignore why I have my formulas in the for loop. Formulas were not working using the declared variables so have just done this in the mean time.
You can use some user defined functions to calculate the conversion from Celsius to the other units.
Then you only need one loop:
#include <iostream>
#include <iomanip>
using std::cout;
using std::cin;
using std::setw;
// define some constant
const double zero_point = 273.15;
constexpr double factor = 9.0 / 5.0;
const double max_cels = 5000;
// farenheit conversion
double cels_to_far( double cels ) {
return cels * factor + 32.0;
}
// kelvin conversion
double cels_to_kel( double cels ) {
return cels + zero_point;
}
// rankine conversion
double cels_to_ran( double cels ) {
return ( cels + zero_point ) * factor;
}
int main()
{
double temp_cels;
double delta_t;
cout << "Enter the temperature in celsius: ";
cin >> temp_cels;
while ((temp_cels < -zero_point) || (temp_cels > 5000)) {
cout << "ERROR: out of range.\n";
cout << "Enter the temperature in celsius: ";
cin >> temp_cels;
}
cout << "Enter the increment value: ";
cin >> delta_t;
cout << "\n # Cels Fahr Kel Rank\n";
// output loop
for ( int i = 0; i < 20; ) {
cout << setw(10) << ++i << std::fixed << std::setprecision(2)
<< setw(10) << temp_cels
<< setw(10) << cels_to_far(temp_cels)
<< setw(10) << cels_to_kel(temp_cels)
<< setw(10) << cels_to_ran(temp_cels) << std::endl;
temp_cels += delta_t;
}
}
The output is as expected ( 50° Celsius and increment of 5°):
# Cels Fahr Kel Rank
1 50.00 122.00 323.15 581.67
2 55.00 131.00 328.15 590.67
3 60.00 140.00 333.15 599.67
4 65.00 149.00 338.15 608.67
5 70.00 158.00 343.15 617.67
6 75.00 167.00 348.15 626.67
7 80.00 176.00 353.15 635.67
8 85.00 185.00 358.15 644.67
9 90.00 194.00 363.15 653.67
10 95.00 203.00 368.15 662.67
11 100.00 212.00 373.15 671.67
12 105.00 221.00 378.15 680.67
13 110.00 230.00 383.15 689.67
14 115.00 239.00 388.15 698.67
15 120.00 248.00 393.15 707.67
16 125.00 257.00 398.15 716.67
17 130.00 266.00 403.15 725.67
18 135.00 275.00 408.15 734.67
19 140.00 284.00 413.15 743.67
20 145.00 293.00 418.15 752.67
You need exactly one for loop, incrementing by x. ( The nested for loops are a mistake )
Start with the one, single for loop that you need: the one that counts through the lines of the output table.
In the body of the loop, calculate everything you need for that line, and output it.
Something like this:
for( int line_count = 0;
line_count < 20;
line_count++ )
{
double line_temp_celsius =
start_celsius + line_count * celsius_increment;
// calculate the other values based line_temp_celsius
...
}
The calculation must be in the loop where you change the value of CELS.
There should be a single loop. The result looks like this. See live demo
for (int i = 1; i <= 20; i++, CELS+=x)
{
double FAR = (CELS * (9.0 / 5) + 32); // farenheit conversion
double KEL = (CELS + 273.15); // kelvin conversion
double RANK = ((CELS + 273.15) * (9.0 / 5)); // rankine conversion
cout << setw(10) << i << setw(10) << CELS << setw(10) << FAR
<< setw(10) << KEL << setw(10) << RANK << endl;
}