I keep getting the error "error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive] " and I do not know why;
I am doing this for homework and we have yet to discuss pointers so using them is out of the question.
here is my code (PS I am new to programming)
#include <iostream>
#include <cmath>
using namespace std;
double normalize (int , int);
double normalize (double,double);
int n=0;
int i=0;
const double SIZE=5;
double mean=0;
double meanDivide;
int main()
{
char dataType;
int norm[5];
int value =1;
cout<<"Which data type do you want (i, d): ";
cin>>dataType;
if (dataType =='i')
{
while(value<5)
{
cout<<"Enter value "<<value << ": ";
cin>> norm[n];
value++;
}
}
else if (dataType=='d')
{
cout<<"Enter value "<<value << ": ";
cin>> norm[n];
value++;
}
cout<<"The mean is: "<<normalize(norm,5)/* The error comes from here and
I do not know what to do or why */
<<endl;
cout<<"The normalized values: "<<endl;
int j=0;
cout<<"norm[1] = "<<norm[j]<<endl;
j++;
cout<<"norm[2] = "<<norm[j]<<endl;
j++;
cout<<"norm[3] = "<<norm[j]<<endl;
j++;
cout<<"norm[4] = "<<norm[j]<<endl;
j++;
cout<<"norm[5] = "<<norm[j]<<endl;
return 0;
}
double normalize(int norm[],int SIZE)
{
while(i<6)
{
meanDivide +=norm[i];
i++;
}
i=0;
while (i<n)
{
norm[i] -=meanDivide;
i++;
}
mean = meanDivide / 5;
return mean;
}
double normalize (double norm[],double SIZE)
{
while(i<6)
{
meanDivide +=norm[i];
i++;
}
i=0;
while (i<n)
{
norm[i] -=meanDivide;
i++;
}
mean = meanDivide / 5;
return mean;
}
This is the output I should be getting.
//For integers:
Which data type do you want (i, d): i
Enter value 1: 0
Enter value 2: 3
Enter value 3: 4
Enter value 4: 8
Enter value 5: 12
The mean is: 5.4
The normalized values:
norm[1] = -5
norm[2] = -2
norm[3] = -1
norm[4] = 2
norm[5] = 6
//For doubles:
Which data type do you want (i, d): d
Enter value 1: 5.5
Enter value 2: 1.23
Enter value 3: 2.02
Enter value 4: 9.99
Enter value 5: 6.32
The mean is: 5.012
The normalized values:
norm[1] = 0.488
norm[2] = -3.782
norm[3] = -2.992
norm[4] = 4.978
norm[5] = 1.308
You are declaring your methods like this :
double normalize (int , int);
double normalize(double*, double);
Yet you are trying to implement them like :
double normalize(int norm[], int SIZE) {/*...*/}
double normalize(double norm[], double SIZE) {/*...*/}
Notice that the argument types are not the same, int, int is not the same as int[], int. This means that your implementation is actually defining a whole new function, unrelated to the ones you declared at the top of your example. When you call your normalize function, only the initial declaration is found, and it tries to match int norm[5] to int which it fails. To fix this, make sure the declaration is correct. Change the declarations to this :
double normalize(int[], int);
double normalize(double[], double);
This will fix the error you are asking about in this question, but your example still has other problems. Some of them are identified in the comments.
You declare prototypes for non-pointer parameters:
double normalize (int , int);
double normalize (double,double);
You call with pointer arguments:
cout<<"The mean is: "<<normalize(norm,5)
The C++ compiler at that point does not care about the implementation with pointer arguments below. Try matching implementation to prototypes.
Also
a) you increment value but use n as index:
cin>> norm[n];
value++;
b) you ignore SIZE
c) SIZE should be unsigned int in both cases
d) your example is not minimal (https://stackoverflow.com/help/mcve)
You might find this generally useful:
https://ericlippert.com/2014/03/05/how-to-debug-small-programs/
Related
I want to find the sum up to the 'n'th term for the following series:
(1/2)+((1*3)/(2*4))+((1*3*5)/(2*4*6))....
So, I wrote the following program in c++ :
#include <bits/stdc++.h>
#include <conio.h>
using namespace std;
int main()
{
int p=1, k=1, n=0;
float h=0;
cout<<"Enter the term: ";
cin>>n;
for(int i=1; i<=n; i++)
{
for(int j=1; j<=i; j++)
{
p*=((2*j)-1);
k*=(2*j);
}
h+=(p/k);
p=1;
k=1;
}
cout<<"The sum is : "<<h;
return 0;
getch();
}
However, the output of the program always gives me '0'. I can't figure out the problem with the program.
N.B. I'm new to programming.
The problem here is that you haven't declared p and k as float or doubleor explicitly cast them as such before the calculation and assignment to h.
What's happening is for every iteration of the loop p < k (by nature of the problem) since p and k are both declared as int, p / k = 0. So you're just summing 0 for every iteration.
Either declare p and k as float or double or do this:
h += ((float) p) / ((float) k)
Also, for this specific problem I assume you're looking for precision, so be wary and look into that as well Should I use double or float?
implicit conversion and type casting are a trap where all newbies fall.
in the instruction:
h += p/k;
the compiler performs an integer division first, then a promotion of the result to floating point type.
and since:
p < k ; for all i,j < n
then:
res = (p / k) < 1 => truncates to 0; // by integer division
thus:
sum(1->n) of p/k = sum (1->n) 0 = 0;
finally:
h = conversion to float of (0) = 0.0f;
that's why you have the result of 0.0f at the end.
the solution:
1- first of all you need to use the natural type for floating point of c++ which is "double" (under the hood c++ promotes float to double, so use it directly).
2- declare all your variable as double, except the number of terms n:
3- the number of terms is never negative, you need to express that in your code by declaring it as an unsigned int.
4- if you do step 3, make sure to catch overflow errors, that is if the user enters a negative number your risk to have a very big number in "n", expel : n =-1 converts to 0xffffffff positive number.
5- engineer your code sometimes is better.
6- include only the headers that you need, and avoid a importing any namespace in your global namespace.
here is how i think you should write your program.
#include <iostream>
double sum_serie(unsigned int n)
{
double prod = 1.0, sum = 0.0;
for (double c=1; c<=n ; c++)
{
prod *= ( ( 2*c ) - 1 ) / ( 2*c ); // remark the parenthesis
sum += prod;
}
return sum;
}
int main()
{
unsigned int n = 0;
int temp = 0;
std::cout << " enter the number of terms n: ";
std::cin >> temp;
if (temp > 0)
n = temp; // this is how you catch overflow
else
{
std::cout << " n < 0, no result calculated " << std::endl;
return 0;
}
std::cout << " the result is sum = " << sum_serie(n) << std::endl;
return 0;
}
I know that the question was about the implicit conversion and casting in C++, but even the way of writing a code can show you what bugs you have in it, so try to learn a proper way of expressing your ideas into code, debugging comes natural afterward.
Good Luck
I was experimenting with classes and I wrote this example code. The user enters their register number and two marks. The output should be their register number and the average of the two input marks. I have two questions:
How do I use the float type to display the output average marks in decimal form if I am using constructors?
Why is the output of the register number not correct? The code is given below.
#include<iostream.h>
#include<conio.h>
class abc
{
int reg, mark1, mark2;
public:
int avg;
abc(int reg, int mark1, int mark2)
{
avg = (mark1 + mark2) / 2;
}
void display()
{
cout<<"Your average mark is:\n"<<avg<<"\n";
cout<<"Your Register Number is:\n"<<reg<<"\n";
}
};
void main()
{
clrscr();
int num, m1, m2;
cout << "Enter your register number\n";
cin >> num;
cout << "Enter your Mark 1 and Mark 2:\n";
cin >> m1 >> m2;
abc s1(num,m1,m2);
s1.display();
getch();
}
I am getting the average (without the decimal) and the register number output is 11196.
In C++ the constructor arguments are not automatically stored in the class members. I would change your class declaration to the following, note that I have used different names for the members and function arguments (I like to use m_ for private member variables).
class abc
{
int m_reg, m_mark1, m_mark2;
public:
int avg;
abc (int reg, int mark1, int mark2)
: m_reg(reg), m_mark1(mark1), m_mark2(mark2)
{
avg = (m_mark1+m_mark2)/2;
}
void display()
{
cout<<"Your average mark is:\n"<<avg<<"\n";
cout<<"Your Register Number is:\n"<<m_reg<<"\n";
}
};
If you expect your result to be a decimal (and not rounded or floored to the nearest integer) you need to change your average declaration and calculation to:
// The new declaration
double avg;
// In your constructor
avg = (double) (m_mark1 + m_mark2) / 2.0;
All you need to do is add value to reg property in your class constructor:
abc (int r, int mark1, int mark2)
{
reg = r;
avg = (mark1+mark2)/2;
}
In addition to that, why is avg an integer instead of double? Consider this:
class abc
{
int reg,mark1,mark2;
public:
double avg;
abc (int r, int mark1, int mark2)
{
reg = r;
avg = (double)(mark1+mark2)/2.00;
}
void display()
{
cout<<"Your average mark is:\n"<<(int)avg<<"\n";
cout<<"Your Register Number is:\n"<<reg<<"\n";
}
};
If you want 4.4 to be displayed as 4, and 4.5 as 5 use this hack:
avg = avg + 0.5;
cout << (int)avg << "\n";
I have a function, fx named and has two input variable as an array and a double, so I wrote my program like this and I am faced with below error. The problem is in definition of input array but I don't know how to solve it.
And another problem is when I want to call this fx function with inputs, how can I give a complete array as the first input variable — fx(matris[n],x)?
error : variable-size type declared outside of any function
Code:
#include<iostream>
using namespace std;
int n=1;
double y=1;
double x;
double fx(double matris[], double x){
double f = 0;
for(int i=0;i<n;i++)//e.g f(X)= 3x^2 + 2x -4 = 0 [3 2 -4]
{
y = 1;
for(int k = 0;k<n-i-1;k++){//temp: y = x*x*x or x*x or x ... (calcules powers)
y = y*x;
}
f = f+y*matris[i];// 3 * y((x*x)) + 2 * y((x)) + -4* y(1)
}
return f;
}
double dif(double matris[], double x){
double temp[n];
temp[0] = 0;
for (int i=0;i<n;i++){
temp [i+1] = matris[i] * (n-i-1);
}
return fx(temp[n], x);
}
int main(){
//newton-raphson method to solve a equilibrium
cout << "please enter the degree of your equilibrium: ";
cin >> n;
double matris[n];
cout << "please enter your equlibruim array: ";
for(int i =0; i<n; i++)
cin >> matris[i];
//x = x0 - f(x)/f'(x);
x = 1;
fx(matris,x);
return 0;
}
Since arrays passed to a function don't actually have a size (variable or otherwise), the compiler objects to you passing a variable n as the size of matris.
Just remove the n from your double matris[n] expression, leaving the square brackets empty.
[Note that the code doing cin > n; double matris[n]; is not standards compliant C++ - C++14 will introduce such a concept, but for existing C++ standards, it is not allowed - only GNU C++ and some "GNU C++ compatible" compilers support this construct].
First time posting so be gentle. I've started to teach myself C++ as I've always had an interest and also it will be useful for work in the future.
Ok so i have written a very basic program that will either Add, Subtract, Multiply or Divide depending on the user input.
My question is can i use an input from the user as string and use that to call a function?
See code below:-
#include <iostream>
#include <string>
using namespace std;
// Addition Function
int Add (int a, int b)
{
int r; //Result
r=a+b; //formula
return r; //return result of formula
}
// Subtraction Function
int Subtract (int a, int b)
{
int r; //Result
r=a-b; //formula
return r; //return result of formula
}
// Multiply Function
int Multiply (int a, int b)
{
int r; //Result
r=a*b; //formula
return r; //return result of formula
}
// Divide Function
int Divide (int a, int b)
{
int r; //Result
r=a/b; //formula
return r; //return result of formula
}
// Main
int main()
{
int ip1, ip2, z;
string option;
cout << "Enter first number: ";
cin >> ip1;
cout << "Enter second number: ";
cin >> ip2;
cout << "What would you like to do?, Please type an option (Options: Add, Subtract, Multiply, Divide)\n";
getline(cin,option);
z = option (ip1,ip2);
cout << "The result is " << z;
}
So i ask the user to type in an option i.e. Add, the program then takes that string(Add) and uses it to call the Add function.
At the moment im getting a 'no match for call to '(std::string {aka std::basic_string}) (int&, int&)' error on compile
Any help would be appreciated
Thanks
Lewis
You can use a pretty simple if conditional tree:
if (option == "Add") z = Add(ip1, ip2);
else if (option == "Subtract") z = Subtract(ip1, ip2);
else if (option == "Multiply") z = Multiply(ip1, ip2);
else if (option == "Divide") z = Divide(ip1, ip2);
Alternatively you can use an std::map to map an std::string to the corresponding function pointer. It possibly cleaner but definitely longer to write:
std::map<std::string, std::function<int(int, int)>> mapping;
mapping["Add"] = &Add;
mapping["Subtract"] = &Subtract;
mapping["Multiply"] = &Multiply;
mapping["Divide"] = &Divide;
if (mapping.find(option) == mapping.end())
// there's no such an option
z = mapping[option](ip1, ip2);
In this particular case you can even do without std::function and just use C function pointers (for non-std::function lovers):
std::map<std::string, int(*)(int, int)> mapping;
On a side note, notice that you can get rid of a lot of lines of code and temporary variables in your function declarations:
int Add (int a, int b) { return a + b; }
int Subtract (int a, int b) { return a - b; }
int Multiply (int a, int b) { return a * b; }
int Divide (int a, int b) { return a / b; }
I am some-what new to Programming in c++ i was assigned a exercise what i'm getting a compile error
i was hoping someone can either help me resolve the error or give me some insight as to why its happening
Code below
/*
Exercise 21 Intermediate: Declare a seven-row, two- column int array named temperatures.
The program should prompt the user to enter the highest and lowest temperatures for seven days.
Store the highest temperatures in the first column in the array.
Store the lowest temperatures in the second column.
The program should display the average high temperature and the average low temperature.
Display the average temperatures with one decimal place.
*/
#include <iostream>
#include <iomanip>
using namespace std;
//function prototype
void calcAverage(double temperatures[7][2]);
main()
{
double temperatures[7][2] = {0};
float high = 0.0;
float low = 0.0;
double high_average = 0.0;
double low_average = 0.0;
cout << "Please enter the high then low for the last 7 days " <<endl;
for(int x = 0; x < 6; x += 1)
{
cout << "Please enter the High for day: "<< x+1<<": ";
cin >> high;
temperatures[0][x] = high;
}
for(int x = 0; x < 6; x += 1)
{
cout << "Please enter the Low for day: "<< x+1<<": ";
cin >> low;
temperatures[1][x] = high;
}
//Error is here
calcAverage(high_average, low_average);
// end error
system("pause");
}
void calcAverage(double temperatures[6][1],double &high_average, double &low_average)
{
float accumulator = 0.0;
//for hot average
for(int x = 0; x < 6; x += 1)
{
accumulator += temperatures[0][x];
}
high_average = accumulator;
// for cold average
accumulator = 0.0;
for(int x = 0; x < 6; x += 1)
{
accumulator += temperatures[1][x];
}
low_average = accumulator;
}
44 cannot convert double' todouble ()[2]' for argument 1' tovoid calcAverage(double ()[2])'
void calcAverage(double temperatures[7][2]);
Okay, calcAverage takes a two-dimensional array of doubles.
calcAverage(high_average, low_average);
But you passed it two doubles.
void calcAverage(double temperatures[6][1],double &high_average, double &low_average)
And now it takes a two-dimensional array of doubles and two references.
Pick one of these three and stick to it.