Number the nearest to the average C++ - 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
}

Related

How to make a while loop till there is something to be readen c++

I know that you probably gona again vote me down, I really don't understand this but im really stuck at something and cant figure it out , there is no such information anywhere in the web , neither in my book for the course, so I have this assignment where I need make 2 sums of containers where the difference between 2 sums is the lowest , so the program is done is working perfectly calculated everything however , in my assignment:
The user enter on one row unkwonw length numbers so after that I do all kind of sums between them and find the one with lowest difference between.
Ok but the way I wrote the code I use one while(true) so that to work with infinity testcases(as from assignment) and in this while(true) I have another while(cin>>(SOMEINT)) loop and push it back in a vector , and after it reads new line it just break the wile and continue with the calculation.
However in our test software this one give runtime error since after finding some cases then it start print infinity 0 0 since there is nothing to enter but the while(true) just continues.
I mean I just want to make it that way that the while is till user enters something , for instance you enter 30 50 90 it will return 80 90 , then wiat for another entry and so on.
CODE:
#include <iostream>
#include <string>
#include<vector>
#include <sstream>
#include <cmath>
#include <string.h>
#include <stdio.h>
#include <climits>
using namespace std;
const int length = 17000;
int power(int x){
int sum =2;
for(int i = 0;i<x;i++) {
sum *= 2;
}
return sum;
}
bool ison(int i,int x)
{
if((i>>x) & 1)return true;
return false;
}
int main()
{
while(true){
vector<int> Vec;
int cur = 0;
while (cin >> cur) {
Vec.push_back(cur);
if (cin.get() == '\n') {
break;
}
}
int * sumOfarr1 = new int[length];
int * sumOfarr2 = new int[length];
for(int i = 0; i<length;i++){
sumOfarr1[i] = 0;
}
for(int i = 0; i<length;i++){
sumOfarr2[i] = 0;
}
int index=0;
for(int i=1;i<length;i++)
{
for(int j=0;j<Vec.size();j++)
{
if(ison(i,j))
{
sumOfarr1[index]+=Vec[j];
}
else
{
sumOfarr2[index]+=Vec[j];
}
}index++;
}
int ans=INT_MAX;
int ii;
for(int i=0;i<index;i++)
{
if(abs(sumOfarr1[i]-sumOfarr2[i])<ans)
{
ii=i;
ans=abs(sumOfarr1[i]-sumOfarr2[i]);
}
}
if(sumOfarr1[ii]<sumOfarr2[ii]){
cout << sumOfarr1[ii] << " " << sumOfarr2[ii];
}
else{
cout << sumOfarr2[ii] << " " << sumOfarr1[ii];
}
cout << endl;
delete[] sumOfarr1;
delete[] sumOfarr2;
Vec.clear();
}
return 0;
}
Yes I found the solution just using getline and stringstream.
aka this
vector<int> Vec;
string line;
while(getline( cin, line ))
{
istringstream iss( line );
int number;
while( iss >> number )
Vec.push_back(number);
}

Polynomial Class runs fine in debugger but not when trying to build&run

So I've been trying to solve this problem for some hours but without any succes. I've got a class for Polynomial methods(set/get grade, set/get polynom's coefficients, print polynom, find every y = f(x) for a given set of numbers etc.)
However, the problem is that whenever the grade of the polynom is even, the build&run returns strange values. The debug of it runs prefectly fine. On the other side, whenever the grade is uneven, works perfectly fine for both debug and build&run. I'm thinking the problem is somewhere at dinamically allocated memory. Here's the code. Thanks
main.cpp
#include "poly_header.h"
int main()
{
Poly p;
p.AfisareValori();
return 0;
}
poly_header.h
#include <iostream>
#include <math.h>
using namespace std;
class Poly
{
private:
int grad;
int* coeficienti;
int a;
int b;
int dx;
public:
Poly();
void SetGrad();
int GetGrad();
void SetCoef();
void GetCoef();
void SetPolyn();
void PrintPoly();
void SetInterval();
void SetDistanta();
void AfisareValori();
~Poly();
};
poly_functions.cpp
#include "poly_header.h"
Poly::Poly()
{
this->grad = 0;
this->coeficienti = new int[0];
}
Poly::~Poly()
{
delete coeficienti;
}
void Poly::SetGrad()
{
int n;
cout<<"Introduceti gradul dorit al polinomului: ";
cin>>n;
this->grad = n;
}
int Poly::GetGrad()
{
cout<<"\n";
return this->grad;
}
void Poly::SetCoef()
{
int n;
this->coeficienti = new int[this->grad];
for(int i = 0; i <= this->grad; i++){
cout<<"Introduceti coeficientul "<<i<<" :";
cin>>this->coeficienti[i];
cout<<"\n";
}
}
void Poly::GetCoef()
{
cout<<"\n";
for(int i = 0; i <= this->grad; i++)
cout<<"Coeficientul asociat termenului x^"<<i<<" este:"<<this->coeficienti[i]<<"\n";
}
void Poly::SetPolyn()
{
SetGrad();
SetCoef();
}
void Poly::PrintPoly()
{
SetPolyn();
for(int i = grad; i >= 0; i--){
if(i == 0){
cout<<coeficienti[i];
break;
}
cout<<coeficienti[i]<<"*X^"<<i<<" + ";
}
}
void Poly::SetInterval()
{
int a,b;
cout<<"Introduceti capatul din stanga al intervalului: ";
cin>>a;
this->a = a;
cout<<"\n";
cout<<"Introduceti capatul din dreapta al intervalului: ";
cin>>b;
this->b = b;
cout<<"\n";
}
void Poly::SetDistanta()
{
int dx;
cout<<"Introduceti distanta dintre puncte: ";
cin>>dx;
this->dx = dx;
cout<<"\n";
}
void Poly::AfisareValori()
{
SetPolyn();
SetInterval();
SetDistanta();
int suma;
for(int i = a; i <= b; i+=dx){
suma = 0;
for(int j = 0; j <= grad; j++){
suma += coeficienti[j] * (pow (i,j));
}
cout<<"Valorea polinomului in punctul "<<i<<" este "<<suma<<"\n";
}
}
A polynomial P of degree ('grad' by your wording) N has N+1 coefficients;
In pseudo code:
length((N, N-1, ... 1, 0)) = N + 1.
thus this
void Poly::SetCoef()
{
/*...*/
this->coeficienti = new int[this->grad];
/*...*/
)
allocates one int too less.
Polynomials of even degree have an odd number N of coefficients, Polynomials of odd degree have an even number of coefficients.
I you allocate an int too less, the bucket too less for the polynomials of odd degree is at an boundary of a 2*sizeof(int) memory alignment; thus, it is likely that that bucket is not used otherwise.
This doesn't hold for even degrees, their missing bucket is within a new alignment block.
That's also the explanation for the discrepancy between debug and release mimics; the debug compiler run simply packs the memory less dense than the release compiler.
Besides that, you don't have to deal with manual field allocation at all for your purpose; e.g. std::vector and std::valarray automate that task in safe manner.

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).

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

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.

Strange output produced by program

I think that my code works. However, it outputs 01111E5, or 17B879DD, or something like that.
Can someone please tell me why.
I am aware that I set the limit of P instead of 10,001. My code is like that because I start with 3, skipping the prime number 2.
#include <iostream>
bool prime (int i)
{
bool result = true;
int isitprime = i;
for(int j = 2; j < isitprime; j++) ///prime number tester
{
if(isitprime%j == 0) result = false;
}
return result;
}
int main (void)
{
using namespace std;
int PrimeNumbers = 1;
int x = 0;
for (int i = 3 ; PrimeNumbers <=10000; i++)
{
if(prime(i))
{
int prime = i;
PrimeNumbers +=1;
}
}
cout<<prime<<endl;
system ("pause");
return 0;
}
cout<<prime<<endl;
prints the address of the function bool prime (int i), not the variable you declared. Just rename the function or the variable (note that you'll also have to change its scope, or move the cout inside the loop - that's if you want to print them all):
for (int i = 3 ; PrimeNumbers <=10000; i++)
{
if(prime(i))
{
cout << i << endl;
PrimeNumbers++;
}
}
Also:
for(int j = 2; j < isitprime; j++) ///prime number tester
{
if(isitprime%j == 0) result = false;
}
could be optimized, since (1) you don't need to check all numbers till isitprime, but at most to sqrt(isitprimt) and (2) you only need to check until result is false, at which point you can break out of the loop.
The output isn't strange at all.
cout<<prime<<endl;
You're printing the function pointer of prime here.
You were probably intending to print the variable you create here:
int prime = i;
But this is in the loop scope. In fact, if you compile with warnings enabled, your compiler should tell you that this variable is never used. Also, it's bad practice to give variables in C or C++ the same name as functions (or any other variable in a higher level scope).
Your loop in the main program does not stop correctly because the test variable, PrimeNumbers may not change.
Try:
for (int i = 3; i < 10000; i++)
{
//...
}
Also, because you declared the variable prime inside an if statement, it disappears after the if statement is executed:
if (prime(i))
{
int prime = i; // <-- Declare the variable before the for loop.
//...
The code for finding prime number from nth to 2(1 is neither prime nor composite) is written below, i havent used math.h header file , did something different and surpizingly it works pretty cool....
Code is:
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
class prime
{
int a;
int i;
public:
void display();
};
void prime::display()
{
cout<<"Enter the number to see primes less than it till 2";
cin>>a;
int count=0;
for(int j=a;j>=1;j--)
{
for(int i=1;i<=j;i++)
{
if(j%i==0)
{
count++;
}
}
if(count==2)
{
cout<<"\t"<<j;
}
count=0;
}
}
void main()
{
clrscr();
prime k;
k.display();
getch();
}
if you want to find the prime number from 1 to n,hope this will help u.
#include <iostream>
#include <vector>
static bool _isprime (int number)
{
if(number==1)
{
return false;
}
bool flag=true;
if(number==2||number%2!=0)
{
for(int i=2;i<number;i++)
{
if(number%i==0)
{
flag=false;
}
}
}
else flag=false;
return flag;
}
int main (void)
{
using namespace std;
vector<int> primenumber;
cout<<"prime number between 1 and ?"<<endl;
int x=0;
cin>>x;
for(int i=0;i<=x;i++)
{
if(_isprime(i)==true)
{
//cout<<x<<" is a prime number"<<endl;
primenumber.push_back(i);
}
//else cout<<x<<" is not a prime number"<<endl;
}
for(int i=0;i<primenumber.size();i++)
{
cout<<primenumber[i]<<endl;
}
cout<<"the number of prime number is "<<primenumber.size()<<endl;
system("pause");
return 0;
}