I am new to c++ and trying to calculate Xk+1 = Xk - a*Xk*h for user entered values. Here's what I tried:
#include<stdio.h>
float fn_calculate(int x1, int x0, int a, float h)
{
int x;
int a;
float h;
int k;
for(k=-1; k<=100; k++);
{
float x1=x0-a*x0*h;
printf("please enter a 'x' value:\n");
scanf("%f",&x);
printf("please enter a 'a' value:\n");
scanf("%f",&a);
printf("please enter a 'h' value:\n");
scanf("%f",&h);
printf("the result is: %f\n", x1);
}
return 0;
}
You declare a inside the function. There's a parameter with the same name, a.
Doing that you cannot access the parameter a but only the local variable defined. You should change the name of either.
The same happens for h. You have to choose different names for both of them.
The right expression with main function is here:
#include<stdio.h>
float fn_calculate() {
float x0;
int k;
float h, a;
for (k = -1; k <= 100; k++);
{
printf("please enter a 'x' value:\n");
scanf("%f", &x0);
printf("please enter a 'a' value:\n");
scanf("%f", &a);
printf("please enter a 'h' value:\n");
scanf("%f", &h);
float x1 = x0 - a * x0 * h;
printf("the result is: %f\n", x1);
}
return 0;
}
int main(){
// you will calculate the formula below.
printf("x_{n+1} = x_{n} - a * x_{n} * h ; \n");
fn_calculate();
return 0;
}
By the way, note these problems below may be good for you:
Add some comments;
Add a main function for your program;
Learn about the parameter passing;
Learn about variable type, like %d for int and %f for float.
Related
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/
I have a problem when I execute the program,the results that I have got is "nan" for the values of vector.I do not exactly where is the mistake. the method distancias generates a correct value but the method variogram does not generate the expected value instead of that generates a value "nan".Sorry for my english.
#include <iostream>
#include <math.h>
//this program is to calculate the kriging puntual
using namespace std;
////
class Points{
private:
float x;
float y;
public:
Points(float a,float b);
Points();
float distancia(float x_1,float y_1);
float variogram(float h);
float valor_1();
float valor_2();
void show(void);
};
Points::Points(){
}
Points::Points(float a,float b){
x=a;
y=b;
}
float Points::distancia(float x_1,float y_1){
float d;
d=pow(pow((x-x_1),2)+pow((y-y_1),2),0.5);
return d;
}
float Points::variogram(float h){
float v,c_0,c_1,a_1;
v=c_0+c_1*(1.5*(h/a_1)-0.5*pow((h/a_1),3));
return v;
}
void Points::show(void){
printf("%.2f,%.2f\n",x,y);
}
float Points::valor_1(){
return x;
}
float Points::valor_2(){
return y;
}
///////
int main(int argc, char** argv) {
float a_1,c_0,c_1; //parameters of variogram
float c,d; // position of point to determinate
float a,b; //positions of all points except the point to determinate
int i=0,n;
int j,k;
Points final; //point to determinate
//this part is to enter the values of function sphere variogram
printf("Enter the paramters of sphere variogram\n");
printf("Enter the value of c_0: ");
scanf("%f",&c_0);
printf("Enter the value of c_1: ");
scanf("%f",&c_1);
printf("Enter the value of a: ");
scanf("%f",&a_1);
//determinating the postion of final point
printf("Enter the position of the point to determinate: ");
scanf("%f,%f",&c,&d);
final=Points(c,d);
final.show();
printf("Enter the name of points for the krigeage: ");
scanf("%i",&n);
Points punto[n];
float vector[n];
do{
printf("Enter the position x,y of the point %i: ",i+1);
scanf("%f,%f",&a,&b);
punto[i]=Points(a,b);
punto[i].show();
vector[i]=punto[i].variogram(punto[i].distancia(c,d));
cout<<vector[i]<<endl;
i=i+1;
}while(i<n);
return 0;
}
The problem is in the following function:
float Points::variogram(float h){
float v,c_0,c_1,a_1;
v=c_0+c_1*(1.5*(h/a_1)-0.5*pow((h/a_1),3));
return v;
}
Here, you are declaring the local variables v, c_0, c_1 and a_1. These values are not initialized, they can contain anything. However, it is not unlikely they actually are equal to zero. So when you calculate h/a_1, the result of that is probably plus or minus infinity. When you subtract two infinities with the same sign from each other, the result will be NaN.
What you should do is pass the values for c_0, c_1 and a_1 from main() to the function:
float Points::variogram(float h, float c_0, float c_1, float a_1){
return c_0+c_1*(1.5*(h/a_1)-0.5*pow((h/a_1),3));
}
...
vector[i]=punto[i].variogram(punto[i].distancia(c,d), c_0, c_1, a_1);
Please compile your code with warnings enabled (if you use GCC, then use the -Wall command line option). Your compiler should then warn you about these uninitialized variables.
Why does this code not work? My IDE is Visual Studio 2013.
#include <stdio.h>
float tempatureGuide(float F, float C);
#define FREEZING_PT 32.0f
#define SCALE_FACTOR (5.0f/9.0f)
int main(void)
{
float fahrenheit = 0.0;
float celsius = 0.0 ;
int convertTemp;
printf ("Enter 0 to calculate Celsius or 1 to calculate Fahrenheit: ");
scanf ("%d", &convertTemp);
if (convertTemp == 0)
{
// compute Celsius
printf("Enter Fahrenheit temperture: ");
scanf("%f", &fahrenheit);
celsius = ((fahrenheit - FREEZING_PT) * SCALE_FACTOR);
printf("Fahrenheit = %f and Celsius = %f\n", fahrenheit, celsius);
float tempatureGuide(fahrenheit, celsius); // Error here
}
else
{
// compute fahrenheit
printf("Enter the temperature in degrees fahrenheit\n\n");
scanf("%f", &fahrenheit);
celsius = (SCALE_FACTOR)* (fahrenheit - FREEZING_PT);
printf("The converted temperature is %f", celsius);
float tempatureGuide(fahrenheit, celsius); // and here
}
return (0);
}
float tempatureGuide(float F, float C){
if (F < 32 || C < 0)
printf("It is freezing!");
else if (F <= 60 || C <= 16)
printf("It is cold");
else if (F >= 70 || C >= 21)
printf("It is just right");
else if (F >= 82 || C >= 28)
printf("It is warm");
else if (F > 95 || C > 35)
printf("It is hot");
else
printf("Please enter a number!");
return (0);
}
The goal here is to add to the converting temperature project I did earlier and add an if else statement function to it that comments on the temp. The error I get is
Error 3 error C2078: too many initializes
on both the lines where I call my function. I searched for an answer but couldn't find any.
This line looks like an attempt at a C++ initialization of a float with one too many arguments (hence the "too many initializers" error), not like a function call.
float tempatureGuide(fahrenheit, celsius);
Presumably you want to call the function and store the result in a variable:
float temp = tempatureGuide(fahrenheit, celsius);
Or just call the function and ignore the return value:
tempatureGuide(fahrenheit, celsius);
Especially since your function always returns 0, so one might question the need for a non-void return type.
You need to call a function
float tempatureGuide(float fahrenheit, float celsius) { //...}
as
float retval = tempatureGuide(fahrenheit, celsius);
or least
tempatureGuide(fahrenheit, celsius); // not need to use return value
Only.
That is just a simple error. Please change 2 lines of code where you are calling tempatureGuide(fahrenheit, celsius); function as follows.
float tempatureGuide(fahrenheit, celsius); --> float ret = tempatureGuide(fahrenheit, celsius);
I tested the same in my VS2013 as you are using the same with the mentioned changes. I am able to compile and run it successfully. See the attachment.
Just call the function and return it to a variable of the same type.
i need to gain a better understanding of function definition, declarations and proper calls using this program. I really need the understanding of how to use them. Could you show me the proper way to write this program with all three correct and explained?
#include <stdio.h>
#include <math.h>
quad_equation(float a, float b, float c);
int main()
{
float a, b, c, determinant, r1,r2;
printf("Enter coefficients a, b and c: ");
scanf("%f%f%f",&a,&b,&c);
determinant=b*b-4*a*c;
if (determinant>0)
{
r1= (-b+sqrt(determinant))/(2*a);
r2= (-b-sqrt(determinant))/(2*a);
printf("Roots are: %.2f and %.2f",r1 , r2);
}
else if (determinant==0) { r1 = r2 = -b/(2*a);
printf("Roots are: %.2f and %.2f", r1, r2);
}
else (determinant<0);
{
printf("Both roots are complex");
}
return 0;
I just solved this exact question here : (I guess this is a part of an assignment )
https://stackoverflow.com/a/19826495/1253932
Also looking at your code .. you never use the function quad equation .. also you haven't defined the type of the function ( int/void/float/char) etc.
For ease: ( here is the entire code ) -- ask me if you don't understand anything
#include <stdio.h>
#include <math.h>
// function declarations
void twoRoots (float a,float b,float delta);
void oneRoot (float a,float b,float delta);
int main (void)
{
//Local Declarations
float a;
float b;
float c;
float delta;
// float solution;
printf("Input coefficient a.\n");
scanf("%f", &a);
printf("Input coefficient b.\n");
scanf("%f", &b);
printf("Input coefficient c.\n");
scanf("%f", &c);
printf("%0.2fx^2 + %0.2fx + %0.2f\n", a, b, c);
delta = (float)(b*b) - (float)(4.0 * a * c);
printf("delta = %0.2f\n",delta);
if (delta > 0){
twoRoots(a,b,delta);
}else if (delta == 0) {
oneRoot(a,b,delta);
}else if (delta < 0.0){
printf("There are no real roots\n");
}
return 0;
}
void twoRoots (float a,float b,float delta)
{
float xOne;
float xTwo;
float deltaRoot;
printf("There are two distinct roots.\n");
deltaRoot = sqrt(delta);
xOne = (-b + deltaRoot) / (2*a);
xTwo = (-b - deltaRoot) / (2*a);
printf("%.2f", xOne);
printf("%.2f", xTwo);
}
void oneRoot(float a,float b,float delta)
{
float xOne;
// float xTwo;
// float deltaRoot;
printf("There is exactly one distinct root\n");
xOne = -b / (2*a);
printf("%.2f", xOne);
}
EDIT:
A slightly more optimized and better functioning code that I made from the above mentioned code:
http://pastebin.com/GS65PvH6
Edit2:
From your comments you try to do this:
printf("Enter coefficients a, b and c: ");
scanf("%f%f%f",&a,&b,&c);
This will fail if you input something like this: 121
Beacuse scanf will read the whole 121 into a and it will have nothing for b,c ( rather it will put \n(enter) into b and undefined into c )
So use the scanf the way I have used it in my code
OK - this is full of problems! I attempt to point them out, and show what "better" looks like. I hope this helps.
quad_equation(float a, float b, float c);
This is probably intended to be a "function prototype". A prototype tells the compiler "I am going to use this function later, and this is how it needs to be called, and the type it returns". You did not specify a return type; probably you want to use int to say whether you found roots or not, and print out the result in the function. Better would be to pass space for two return values as a parameter:
int quad_equation(float a, float b, float c, float* x1, float* x2);
Now we can use the main program to get input/output, and let the function solve the problem:
int main(void) {
{
float a, b, c, r1, r2;
int n;
// here you get the inputs; that seems OK
printf("Enter coefficients a, b and c: ");
scanf("%f %f %f",&a,&b,&c);
// now you have to "call your function"
// note that I make sure to follow the prototype: I assign the return value to an int
// and I pass five parameters: the coefficients a, b, c and the address of two variables
// x1 and x2. These addresses will be where the function puts the roots
n = quad_equation(a, b, c, &r1, &r2);
// when the function returns, I can print the results:
printf("There are %d roots:\n", n);
// based on the value of n, I change what I want to print out:
if (n == 2) printf(" %f and ", r1); // when there are two roots I print "root 1 and"
if (n > 0) printf("%f\n", r2); // when there is at least one root, I print it
// note that if n == 0, I would skip both print statements
// and all you would have gotten was "There are 0 roots" in the output
}
int quad_equation(float a, float b, float c, float* x1, float* x2) {
// function that computes roots of quadratic equation
// and returns result in x1 and x2
// it returns the number of roots as the return value of the function
float determinant;
determinant=b*b-4*a*c;
if (determinant>0)
{
*x1 = (-b+sqrt(determinant))/(2*a);
*x2= (-b-sqrt(determinant))/(2*a);
return 2;
}
if (determinant==0) {
*x1 = *x2 = -b/(2*a);
return 1;
}
return 0;
}
I am learning the basics for programming in C++ and I need to write a program that performs some basic math functions using if/else statements: subtraction, addition, multiplication ect. I don't get any compile or run time errors, but the values that I end up with are always incorrect.
I changed some things around trying to see where I went wrong but what is printed on the screen as far as words go are correct just not the answers. For instance when I scan a - (subtraction sign) as input it will read the difference between x and y is some ridiculously high number.
Anyway, here is my code & any help would be GREATLY appreciated!
/*
* This program performs some basic math calculations
*/
#include <stdio.h>
#include <math.h>
int main() {
int x,y;
float sum = x+ y;
float difference = x-y;
float product = x*y;
float quotient = x/y;
float exponent = x^y;
float modulus = x%y;
char symbol;
printf("What is the value of x?\n");
scanf("%d", &x);
printf("What is the value of y?\n");
scanf("%d", &y);
printf("What is your operator?\n");
scanf(" %c", &symbol);
if (symbol== '+')
printf("The sum of x and y = %f\n", sum);
else if (symbol=='-')
printf("The difference between x and y = %f\n", difference);
else if (symbol=='*')
printf("The product of x and y = %f\n", product);
else if (symbol=='/')
printf("x divided by y = %f\n", quotient);
else if (symbol=='^')
printf("x multiplied exponentially by y = %f\n", exponent);
else if (symbol=='%')
printf("x is this much percent of y =%f\n", modulus);
return 0;
}
Sine this is a C++ application you can define variables as you want. But keep in mind that a program written in C or C++ and for all other languages will be executed top to bottom so when you declare x and y they has no value read from the user. Always trace your codes from top to bottom. Here I declare x and y and read their values from the user first. Then I calculate their different operations. I think most of them except division can be integers again like x and y but I tries to correct your code.
If you want to have exponentiation in C or C++ you have to write your own code.
#include <stdio.h>
#include <math.h>
float power( int x , int y )
{
float ret = 1 ;
for( int i = 1 ; i <= y ; i++ )
ret *= x ;
return ret ;
}
int main() {
int x,y;
printf("What is the value of x?\n");
scanf("%d", &x);
printf("What is the value of y?\n");
scanf("%d", &y);
printf("What is your operator?\n");
scanf(" %c", &symbol);
float sum = (float)x+ y;
float difference = (float)x-y;
float product = (float)x*y;
float quotient = (float)x/y;
//float exponent = (float)x^y; //Exponentiation should be implemented using multiplication and loops.
float exponent = power( x , y ) ;
float modulus = (float)x%y;
char symbol;
if (symbol== '+')
printf("The sum of x and y = %f\n", sum);
else if (symbol=='-')
printf("The difference between x and y = %f\n", difference);
else if (symbol=='*')
printf("The product of x and y = %f\n", product);
else if (symbol=='/')
printf("x divided by y = %f\n", quotient);
else if (symbol=='^')
printf("x multiplied exponentially by y = %f\n", exponent);
else if (symbol=='%')
printf("x is this much percent of y =%f\n", modulus);
return 0;
}
You are performing ALL of the calculations even before you've initialized x and y. Uninitialized variables have indeterminate contents and thus any result you have are indeterminate. You are running the risk of invoking Undefined Behavior with some of your statements (which means that it is impossible to say what your code will do with any amount of certainty). Do your operations only after you've read in the values of x and y.
#include <math.h>
Why do you have this include if you don't use any functions from <math.h>?
float sum = x+ y;
The sum (or difference) of two integers will always be an integer. Why are you using a float here?
float quotient = x/y;
This does integer division and the result is converted to a float. So, the results may not be what you intend. Try to convert any one of the arguments to a float/double in order to get the correct result. Also, you should always check for division by zero. Same goes for your modulus calculation.
float exponent = x^y;
There is no exponentiation operator in C. You need to use a library function (such as pow) or roll your own.
scanf(" %c", &symbol);
Why do you have the space in front?
There is also no need for this huge if-else ladder. Try using a switch.
You need to pick up a good book and start reading to understand how C works.