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;
}
Related
I am new at this and I don't even know really know what I am doing yet. But I have an assignment to create a program that simulates the rolling of two dice. The program should call rand to roll the first dice, and should call rand again to roll the second dice.
Here's what I've done so far:
//rolling two dice 40000 times
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int main ()
{
int face1=0, face2=0, sum=0, roll=40000;//declaring variables and total rolls
srand (time(NULL));//setting random number
while (roll>0){
face1 =rand()% 6 + 1;
cout<<"Your first roll is " <<face1<< endl;
face2 =rand()% 6 + 1;
cout<<"You second roll is" <<face2<< endl;
sum = face1+face2;//sum of rolls
cout <<endl;
}
return 0;
}
I don't really know if it's even right but I am more confused with the last part of the question which is:
Use a single-subscripted array to tally the numbers of times each sum appears. Print the results in a tabular format. Also, determine if the totals are reasonable, ( i.e, there are six ways to roll a 7), so approximately 1/6 of all the rolls should be a 7.
How do I do that?
First we need to fix a major problem in your code. You have an endless loop, because you never decrement the vaiable roll.
So, you need to change the corresponding statement to: while (roll-- > 0) {.
Then, you should count the numbers of different sums. Possible outcomes of sums are values between 2 and 12.
So, we need an array to store the count of the sums. Normally only 11 elements would be needed. But, for convenience, we use 13 elements, so that we can directly use the sum as an index into the array. Please remember: Array indices start with 0 in C++.
Example:
int sumCounter[13]{};
// Roll your dices
// Then count
++sumCounter[sum];
The {} will initialize all values of the array to 0.
Let us do this first.
Then next, we need to check the probability for a sum. Overall you can have 6 * 6 = 36 possible results with 2 dices. We are talking about ordred pairs here. To calculate the theoretical probabilities, we will count again sums for all possible outcomes.
This can be done like this:
int potentialSumCounter[13]{};
for (int d1 = 1; d1 <= 6; ++d1)
for (int d2 = 1; d2 <= 6; ++d2)
++potentialSumCounter[d1 + d2];
std::cout << "\n\nTheroretical count of sums:\n";
for (int k = 2; k <= 12; ++k) {
std::cout << "Sum: " << k << "\tCount: " << potentialSumCounter[k] << '\n';
}
Then, we multiply the this theoretical value with the number of experiments and calculate the delta between therotical and actual in percent.
Result could look like this:
//rolling two dice 40000 times
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
constexpr int NumberOfTests = 40000;
int main()
{
int face1 = 0, face2 = 0, sum = 0, roll = NumberOfTests;//declaring variables and total rolls
srand(time(NULL));//setting random number
int sumCounter[13]{};
while (roll-- > 0) {
face1 = rand() % 6 + 1;
//cout << "Your first roll is " << face1 << endl;
face2 = rand() % 6 + 1;
//cout << "You second roll is" << face2 << endl;
sum = face1 + face2;//sum of rolls
++sumCounter[sum];
//cout << endl;
}
// Show result of rolling dices. Show number of different sums
std::cout << "\n\nResult of experiment. Count of sums:\n";
for (int k = 2; k <= 12; ++k) {
std::cout << "Sum: " << k << "\tCount: " << sumCounter[k] << '\n';
}
// Get theroretical values
int potentialSumCounter[13]{};
for (int d1 = 1; d1 <= 6; ++d1)
for (int d2 = 1; d2 <= 6; ++d2)
++potentialSumCounter[d1 + d2];
std::cout << "\n\nTheroretical count of sums:\n";
for (int k = 2; k <= 12; ++k) {
double theroretical = 1.0*potentialSumCounter[k] * NumberOfTests / 36;
int deltaToExperimental = std::abs(potentialSumCounter[k] - theroretical);
double delta = (1.0*deltaToExperimental / sumCounter[k])*100;
std::cout << "Sum: " << k << "\tCount: " << sumCounter[k]
<< "\tTheoretical: " << theroretical << "\tAccuracy: " << delta << "%\n";
}
return 0;
}
One possible outcome:
Theroretical count of sums:
Sum: 2 Count: 1129 Theoretical: 1111.11 Accuracy: 98.3171%
Sum: 3 Count: 2286 Theoretical: 2222.22 Accuracy: 97.1129%
Sum: 4 Count: 3387 Theoretical: 3333.33 Accuracy: 98.3171%
Sum: 5 Count: 4530 Theoretical: 4444.44 Accuracy: 98.0132%
Sum: 6 Count: 5539 Theoretical: 5555.56 Accuracy: 100.199%
Sum: 7 Count: 6650 Theoretical: 6666.67 Accuracy: 100.15%
Sum: 8 Count: 5562 Theoretical: 5555.56 Accuracy: 99.7843%
Sum: 9 Count: 4353 Theoretical: 4444.44 Accuracy: 101.999%
Sum: 10 Count: 3275 Theoretical: 3333.33 Accuracy: 101.679%
Sum: 11 Count: 2172 Theoretical: 2222.22 Accuracy: 102.21%
Sum: 12 Count: 1117 Theoretical: 1111.11 Accuracy: 99.3733%
#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
I've already had searched around the internet for some answers, but I can't seem to find the answer. I guess this program would be easier if I use for loop but my professor ordered us to use the while loop statement.
#include <iostream>
using namespace std;
int main()
{
float value[10];
float average;
float min;
float max;
int index1 = 0, index2 = 0, index3 = 0, index4 = 0, sum;
while (index1 < 10)
{
cout << "Enter a value : ";
cin >> value[index1];
index1++;
}
while (index2 < 10)
{
sum += value[index2];
index2++;
}
max = value[index3];
while (index3 < 10)
{
if (max < value[index3])
{
max = value[index3];
}
index3++;
}
min = value[index4];
while (index4 < 10)
{
if (min > value[index4])
{
min = value[index4];
}
index4++;
}
average = sum / 10;
cout << "The average is : " << average << "\n";
cout << "The largest value is : " << max << "\n";
cout << "The smallest value is : " << min << "\n";
}
Here's how it looks when I run it.
Enter a value : 98
Enter a value : 45
Enter a value : 32
Enter a value : 21
Enter a value : 67
Enter a value : 54
Enter a value : 74
Enter a value : 25
Enter a value : 98
Enter a value : 33
The average is : -2.00668e+008
The largest value is : 98
The smallest value is : 21
You are seeing the result of integer division, and uninitialized variables. Divide by 10.0 rather than 10 so that compiler coerces both values to a floating point number. Also assign 0 to sum when you are declaring it.
I am assuming there are other warnings too in your program since you are implicitly assigning floating point values to an integer too.
Move variables outside of the main function globally and there is no need to initialize them. Also, you can do calculations using only one loop.
#include <iostream>
using namespace std;
float value[10], average, min, max, sum;
int index;
int main()
{
while (index < 10)
{
cout << "Enter a value : ";
cin >> value[index];
if (value[index] > max) max = value[index];
if (value[index] < min) min = value[index];
sum += value[index];
index++;
}
average = sum / 10.0;
cout << "The average is : " << average << "\n";
cout << "The largest value is : " << max << "\n";
cout << "The smallest value is : " << min << "\n";
}
sum should be equal to zero at point of declaring otherwise it will have garbage value.
int index1 = 0, index2 = 0, index3 = 0, index4 = 0, sum = 0;
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;
}
Basically I just started doing C++ again after a while because I need to (Degree sorta commands it) and I have been tasked with a simple task of writing a simple program that would take a function and use 2 integer inputs (N and M), returning a double output (S). In one part I am asked to to use a loop to display values for S all the way up to N=10 from N=0 for the value M=10
Ive run into a problem where the return give the value "5" for every N up to 10.
This is the code: (do not mind the comments)
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cmath>
//Function, Part A
double func_18710726(int N, int M)
{
double S = 0;
for (int n = 1; n <= N; n++)
for (int m = 1; m <= M; m++)
{
S = S + (sqrt(m*n)+exp(sqrt(m))+ exp(sqrt(n)))/(m*n + 2);
}
return S;
}
//Part B
double func_18710726(int, int);
using namespace std;
int main()
{
int N, M;
double S;
//Part B1
do {
cout << "Enter Value of N for N > 0 and an integer" << endl;
cin >> N;
} while (N <= 0);
do {
cout << "Enter value of M for M > 0 and an integer" << endl;
cin >> M;
} while(M <= 0);
//Part B2
S = func_18710726(N, M);
cout << "The Summation is ";
cout << fixed << setprecision(5) << S << endl;
//Part B3
ofstream output;
output.open("Doublesum.txt");
M = 1;
for (int n = 1; n <= 10; n++)
{
S = func_18710726(n, M);
cout << "The summation for N = " << n << " is ";
cout << fixed << setprecision(5) << 5 << endl;
output << fixed << setprecision(5) << 5 << endl;
}
output.close();
return 0;
}
The output gives me:
Enter Value of N for N > 0 and an integer
1
Enter value of M for M > 0 and an integer
2
The Summation is 4.20696
The summation for N = 1 is 5
The summation for N = 2 is 5
The summation for N = 3 is 5
The summation for N = 4 is 5
The summation for N = 5 is 5
The summation for N = 6 is 5
The summation for N = 7 is 5
The summation for N = 8 is 5
The summation for N = 9 is 5
The summation for N = 10 is 5
--------------------------------
Process exited after 2.971 seconds with return value 0
Press any key to continue . . .
Any help as to why this is happening is much appreciated.
The Question itself
I am sorry if I posted this in the wrong place, if I do, Mods please go easy on me :)
This line:
cout << fixed << setprecision(5) << 5 << endl;
has 5 (five) as its output - you want S (esss)
Probably S is not such a great name for a variable (neither is l)