Issue with `int` vs. `double` - why isn't my program working? - c++

I have just started teaching myself C++ after 2+ years of working with MATLAB and wanting something a little more robust. I am currently using code::blocks with MinGW I am trying to get the hang of using int and double, but for some reason my little test program won't work.
The program was a way for me to practice using functions. The program takes in numbers from the user and stops when a negative number is inserted. Then, it spits out the sum of the input numbers, product of input numbers, and a count of the numbers processed.
When I use only int, the program works as intended, but can't handle any "decimal" numbers thrown at it - it freaks out.
#include <cstdio>
#include <iostream>
#include <cstdlib>
using namespace std;
int X;
int sum;
int product;
int SUM()
{
int A = sum+X;
sum = A;
}
int PRODUCT()
{
int B=product*X;
product = B;
}
int main()
{
cout<<"Welcome to my counting program! "<<endl;
sum = 0;
product = 1;
int counter = 0;
for (;;)
{
cout<<"Give me a number: ";
cin>>X;
if (X<0)
{
break;
}
sum = SUM();
product = PRODUCT();
counter = counter+1;
}
cout<<"SUM: ";
cout<< sum <<endl;
cout<<"PRODUCT: ";
cout<< product <<endl;
cout<<"NUMBERS INPUT: ";
cout<< counter <<endl;
system ("PAUSE");
}
However, when I use double where applicable, the program only gives me zeroes for the product and sum.
#include <cstdio>
#include <iostream>
#include <cstdlib>
using namespace std;
double X;
double sum;
double product;
int SUM()
{
double A = sum+X;
sum = A;
}
int PRODUCT()
{
double B=product*X;
product = B;
}
int main()
{
cout<<"Welcome to my counting program! "<<endl;
sum = 0.0;
product = 1.0;
double counter = 0.0;
for (;;)
{
cout<<"Give me a number: ";
cin>>X;
if (X<0)
{
break;
}
sum = SUM();
product = PRODUCT();
counter = counter+1;
}
cout<<"SUM: ";
cout<< sum <<endl;
cout<<"PRODUCT: ";
cout<< product <<endl;
cout<<"NUMBERS INPUT: ";
cout<< counter <<endl;
system ("PAUSE");
}
What am I doing wrong? what do I need to change to make it work?
Also, I think I am calling my functions incorrectly and trying to pass values between them incorrectly - what is the correct way to do so?

You're still returning int from your functions. Also, since you're assigning the results, you need to return an appropriate value (sum = SUM();).
Try the following changes:
double /*int*/ SUM()
{
double A = sum+X;
sum = A;
return sum; // Return a value!
}
double /*int*/ PRODUCT()
{
double B=product*X;
product = B;
return product; // Return a value!
}
I would also recommend avoiding the globals for sum/product/X, and instead declare them local to your functions, and pass them as arguments to your methods.

Related

Take the sum of two integers and add another integer to the sum continuously

I would like to make a C++ program that takes the sum of two integers and adds another integer to the sum continuously. Please help, I'm a beginner. My code looks like this, except it doesn't update the next sum:
#include <iostream>
using namespace std;
int main() {
int x;
while (cin>>x){
int y=100;
int sum;
sum = x+y;
cout<<sum<<endl;
}
return 0;
}
Your sum variable is declared inside the loop body, so it will be wiped out on each iteration. You need to move that variable outside of the loop, eg:
#include <iostream>
using namespace std;
int main() {
int sum = 100, x;
while (cin >> x){
sum += x;
cout << sum << endl;
}
return 0;
}

Number the nearest to the average C++

does anybody knows what is wrong with 'else' gap and the script inside to show which number is the nearest to the average? I tried to fix it, however there was no better result. (It indicates the number, but wrongly)
#include <iostream>
#include <math.h>
using namespace std;
float average (float *a, int lib)
{
float suma=0;
for (int i=0;i<lib;i++)
{
suma+=*a;
a++;
}
cout<<endl;
return suma/lib;
}
int ile;
int main()
{
float *number;
cout << "quantity of numbers: ";
cin>> ile;
cout<<endl;
number=new float [ile];
for (int i=0; i<ile; i++)
{
cout<<"Give number: ";
cin>>number[i];
}
double b=number[0];
if (ile==2) {
cout<<"liczby "<<number[0]<<" oraz "<<number[1]<<" sa w tej samej odleglosci liczbowej od sredniej!";
}
if (ile==1) {
cout<<"liczba "<<number[0]<<" jest w tej najbliższej odleglosci liczbowej od sredniej!";
}
And here we go (upper there already is double b=number[0];)
else {
double a=average(number,ile);
That is supposed to show the number the nearest to the average
for (int i=0;i<ile;i++)
{
if ((fabs(a-b))<=(fabs(a-number[i]))) {
b=b;
}
else if ((fabs(a-b))>(fabs(a-number[i]))) {
b=liczba[i];
}
i++;
}
}
cout<<b;
delete [] number;
return 0;
}
Thanks in advance for any help
the problem with your code is that you increment the i two times
first int the for lop itself
and the second time after the if else statment
you for loop need to look like that:
for (int i=0;i<ile;i++)
{
if ((fabs(a-b))<=(fabs(a-number[i]))) {
b=b;
}
else if ((fabs(a-b))>(fabs(a-number[i]))) {
b=liczba[i];
}
//i++; <-- delete this one
}

fibonacci sequence sum total error

#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int last;
do{
system("cls");
cout<<" FIBONACCI "<<endl;
int a,sum;
cout<<"Enter the number of outputs you want to be displayed : ";
cin>>a;
long long unsigned int b= 0, c=1;
while(a >=0)
{
cout<<b<<endl;
sum+=b;
b=b+c;
c=b-c;
a--;
}
cout<<"total = "<<sum<<endl;
cin>>last;
}
while(last==0);
system("pause");
return 0;
}
whenever i want to repeat it by giving 0 as the last input the value of sum doesn't reset itself and the new sum gets added to the previous one and a wrong value is displayed as the total.
your variable sum is not initialized before you access it.
You should change
int a,sum;
to
int a;
int sum = 0;
You have declared sum incorrectly it should be the same type as b and c
long long unsigned int sum;
and sum was uninitialised too, but: your calculation is very strange
sum+=b;
b=b+c;
c=b-c;
So I recommend
sum = c + b;
b = c;
c = sum;
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int last;
do{
system("cls");
cout<<"FIBONACCI \n\n";
int a,sum;
cout<<"Enter the number of outputs you want to be displayed : ";
cin>>a;
long long unsigned int sum=0,b=0,c=1,d=0;
while(a >=0)
{
cout<<b<<endl;
sum+=b;
b=d+c;
c=d;
d=b;
a--;
}
cout<<"total = "<<sum<<endl;
cin>>last;
}
while(last==0);
system("pause");
return 0;
}
the change was made in calculation and sum is initialised to zero in beg of the do..while loop and sorry for bad punctuation

ld returned 1 error exit status C++

I keep getting "undefined reference to 'x'" where x is the function prototypes. I have the functions mapped out but the main still needs work just fyi. I just want to fix the ld return error 1 before pressing on but I can't seem to pin point the issue.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
//Symbolic Constants
const int MAX=11;
//Function Prototypes
int buildQuizArray(int);
void printArray(string,int,int);
double calcQuizAverage(int,int);
void sortArray(int,int);
int main ()
{
int quizScores[MAX];
int compQuiz;
int tempArray[MAX];
int average;
compQuiz = buildQuizArray(quizScores[MAX]);
quizScores[MAX]=tempArray[MAX];
average = calcQuizAverage(quizScores[MAX], compQuiz);
cout<<endl<<"Your quiz average is "<<average<<endl;
printArray ("Quiz Scores", tempArray[MAX], compQuiz);
sortArray(tempArray[MAX], compQuiz);
}
int buildQuizArray(int quizArray[])
{
int numQuiz, input, a;
a=0;
numQuiz=1;
cout << "Enter your score for quiz "<<numQuiz<<" (-1 to quit): ";
cin >> input;
while (input != -1)
{
quizArray[a] = input;
a++;
numQuiz++;
cout<< "Enter your score for quiz "<<numQuiz<<" (-1 to quit): ";
cin >> input;
}
return a+1;
}
void printArray(string reportTitle, int quizArray[], int numberOfQuizzes)
{
int a;
cout<< reportTitle <<endl<<"-----------"<<endl;
for (a=0; a<numberOfQuizzes; a++)
{
cout<< "Quiz " << a <<": " << setw(2) <<quizArray[a] <<"/10"<<endl;
}
}
double calcQuizAverage(int quizArray[], int numberOfQuizzes)
{
int sum, lowSum, avg, a;
a = 0;
sum = 0;
lowSum = quizArray[0] + quizArray[1];
for (a=0; a< numberOfQuizzes; a++)
{
sum += quizArray[a];
}
if (numberOfQuizzes <= 2)
{
avg = sum / (10 * numberOfQuizzes) * 100;
}
else
{
(sum - lowSum) / (10 * (numberOfQuizzes - 2)) * 100;
}
return avg;
}
void sortArray(int quizArray[], int numberOfQuizzes)
{
int min, a, b, temp;
for (a=0; a<numberOfQuizzes; a++)
{
min = a;
}
for(b=a+1; b<numberOfQuizzes; a++)
{
if (quizArray[a] < quizArray[min])
{
min = b;
}
}
temp = quizArray[a];
quizArray[a]=quizArray[min];
quizArray[min]=temp;
}
You declare:
int buildQuizArray(int);
But you define:
int buildQuizArray(int quizArray[]) ...
int[] is not the same as int.
Also: You are passing an int to the functions when you call them, though; note that e.g. quizScores[MAX] is the MAXth element of quizScores and is an int, which is actually beyond the end of that array, and really isn't what you want to be doing.
If I had to guess how you got here I'd guess that you had just about everything right, but you had unknowingly declared your prototypes incorrectly (int instead of int[]), so you then tacked [MAX] on to the arrays you were passing to functions just to get it to compile, then ran into the inevitable linker problem that led you here. If that's what you did, it wasn't quite the right approach.
What you really mean to do is:
For your functions that take arrays, declare them properly:
int buildQuizArray (int[]);
Pass the array pointer itself to the function when calling it:
buildQuizArray(quizScores);
Leave your declarations as-is, they look fine (syntax-wise).

Calculating a conditional probability that is similar to a binomial sum

I am considering a society where there are an arbitrary number of people. Each person has just two choices. Either he or she stays with her current choice or she switches. In the code that I want to write, the probability that the person switches is inputted by the user.
To make clear what I am trying to do, suppose that the user tells the computer that there are 3 people in the society where the probabilities that each person chooses to switch is given by (p1,p2,p3). Consider person 1. He has probability of p1 of switching. Using him as a base for our calculation, the probability given person 1 as a base, that exactly no one in the society chooses to switch is given by
P_{1}(0)=(1-p2)*(1-p3)
and the probability using person 1 as a base, that exactly one person in the society chooses to switch is given by
P_{1}(1)=p2*(1-p3)+(1-p2)*p3.
I can't figure out how to write this probability function in C++ without writing out every term in the sum. I considered using the binomial coefficient but I can't figure out a closed form expression for the sum since depending on user input, there are arbitrarily many probabilities that need to be considered.
I have attached what I have. The probability function is only a part of what I am trying to do but it is also the hardest part. I named the probability function probab and what I have in the for loop within the function is obviously wrong.
EDIT: Basically I want to calculate the probability of choosing a subset where each element in that subset has a different probability of being chosen.
I would appreciate any tips on how to go about this. Note that I am a beginner at C++ so any tips on improving my programming skills is also appreciated.
#include <iostream>
#include <vector>
using namespace std;
unsigned int factorial(unsigned int n);
unsigned int binomial(unsigned int bin, unsigned int cho);
double probab(int numOfPeople, vector<double> probs, int p, int num);
int main() {
char correctness;
int numOfPeople = 0;
cout << "Enter the # of people: ";
cin >> numOfPeople;
vector<double> probs(numOfPeople); // Create a vector of size numOfPeople;
for (int i = 1; i < numOfPeople+1; i++) {
cout << "Enter the probability of person "<< i << " will accept change: ";
cin >> probs[i-1];
}
cout << "You have entered the following probabilities of accepting change: (";
for (int i = 1; i < numOfPeople+1; i++) {
cout << probs[i-1];
if (i == numOfPeople) {
cout << ")";
}
else {
cout << ",";
}
}
cout << endl;
cout << "Is this correct? (Enter y for yes, n for no): ";
cin >> correctness;
if (correctness == 'n') {
return 0;
}
return 0;
}
unsigned int factorial(unsigned int n){ // Factorial function
unsigned int ret = 1;
for(unsigned int i = 1; i <= n; ++i) {
ret *= i;
}
return ret;
}
unsigned int binomial(unsigned int totl, unsigned int choose) { // Binomial function
unsigned int bin = 0;
bin = factorial(totl)/(factorial(choose)*factorial(totl-choose));
return bin;
}
double probab(int numOfPeople, vector<double> probs, int p, int num) { // Probability function
double prob = 0;
for (int i = 1; i < numOfPeople; i++) {
prob += binomial(numOfPeople, i-1)/probs[p]*probs[i-1];
}
return prob;
}
For future reference, for anybody attempting to do this, the probability function will look something like:
double probability (vector<double> &yesprobabilities, unsigned int numOfPeople, unsigned int yesNumber, unsigned int startIndex) {
double kprobability = 0;
// Not enough people!
if (numOfPeople-1 < yesNumber) {
kprobability = 0;
}
// n == k, the only way k people will say yes is if all the remaining people say yes.
else if (numOfPeople-1 == yesNumber) {
kprobability = 1;
for (int i = startIndex; i < numOfPeople-1; ++i) {
kprobability = kprobability * yesprobabilities[i];
}
}
else if (yesprobabilities[startIndex] == 1) {
kprobability += probability(yesprobabilities,numOfPeople-1,yesNumber-1,startIndex+1);
}
else {
// The first person says yes, k - 1 of the other persons have to say yes.
kprobability += yesprobabilities[startIndex] * probability(yesprobabilities,numOfPeople-1,yesNumber-1,startIndex+1);
// The first person says no, k of the other persons have to say yes.
kprobability += (1 - yesprobabilities[startIndex]) * probability(yesprobabilities,numOfPeople-1,yesNumber,startIndex+1);
}
return probability;
}
Something called a recursive function is used here. This is completely new to me and very illuminating. I credit this to Calle from Math stack exchange. I modified his version slightly to take vectors instead of arrays with some help.