im trying to calculate the fraction with structs, the compiler says that initializer list cannot be converted, whats actually the issue? here is my code
#include <stdio.h>
struct fraction{
int z = 0;
int n = 1;
};
struct fraction addition(struct fraction b1, struct fraction b2) {
struct fraction result;
result.z = b1.z*b2.n + b2.z*b1.n;
result.n = b1.n*b2.n;
return result;
}
void Print(struct fraction b) {
printf("%d/%d\n", b.z, b.n);
}
int main() {
int i;
struct fraction b1 = { 1,1 }, b2 = { 1,2 };
try {
for (i = 1; i <= 6; i++) {
Print(addition(b1, b2));
}
}
catch (int exception) {
printf("Program closed!");
}
}
the for loop by the way is harmonic series but im not done with it yet. thanks for help in advance
Remove assigned values from struct (for C++11 and below):
struct fraction{
int z;
int n;
};
Now it compiles fine, tested with g++ 5.2.1 (should get the job done for other compilers too).
When I added option -std=c++14 your code compiled just fine without any changes.
When you use C++, you don't need to use struct fraction. You can but you don't need to. You can use just fraction.
Coming to the problematic line:
struct fraction b1 = { 1,1 }, b2 = { 1,2 };
You can use:
fraction b1{ 1,1 };
fraction b2{ 1,2 };
or
fraction b1 = fraction{ 1,1 }, b2 = fraction{ 1,2 };
from http://en.cppreference.com/w/cpp/language/aggregate_initialization
I read that user defined constructors will stop you from initializing with braces and, I guess, initializing your variables in the struct will act like an user defined constructor.
no user-provided constructors (explicitly defaulted or deleted constructors are allowed) (since C++11)
so writing just :
struct fraction{
int z;
int n;
};
should solve the problem
here is my idea how you could solve the problem
#include "stdafx.h"
int euclid( int a, int b );
struct fraction {
int z;
int n;
};
typedef struct fraction Bruch;
Bruch add( Bruch b1, Bruch b2 ) {
Bruch r;
r.z = b1.z * b2.n + b2.z * b1.n;
r.n = b1.n * b2.n;
return r;
}
void print( Bruch b ) {
printf("%d / %d \n", b.z, b.n );
}
void test() {
Bruch eins = {1,1};
Bruch halb = {1,2};
printf(" ---------------- structure---------------- \n" );
Bruch sum = add( eins, halb );
print(sum);
sum.z = 0;
sum.n = 1;
Bruch summand = {1,1};
for( int n=1; n<=6; ++n ) {
summand.nenner = n;
sum = add( sum, summand );
print(sum);
}
}
Related
I'm trying to implement polynomials in C but Im having an issue with arrays and setting values. Im bad at C, please explain why this is happening: I run this, it says that p.coefs[1] is 0.0 instead of 3.0 as intended.
#include <stdio.h>
#include <assert.h>
int main()
{
#define MAX_DEG 10
typedef struct Polynomial Polynomial;
struct Polynomial {
int deg;
double coefs[MAX_DEG];
};
Polynomial ply_create(int deg) {
assert(deg >= 0 && deg <= MAX_DEG);
Polynomial poly;
poly.deg = deg;
return poly;
}
void ply_set_coef(Polynomial poly, int i, double val) {
poly.coefs[i] = val;
}
Polynomial p = ply_create(1);
p.coefs[0] = 1.0;
ply_set_coef(p, 1, 3.0);
printf("p.coefs[0] is %f and p.coefs[1] is %f", p.coefs[0], p.coefs[1]);
return 0;
}
I was previously using malloc and made p.coefs a pointer to a double. In this case I did not have any problem.
I'm fairly new to C/C++, but I'm trying to debug some code. It uses a vector that someone had called CART8 and is structured as such:
typedef struct crt8 {
double x;
double y;
double z; } CART8;
Now my question is this. How do I create and populate an instance of an vector of type CART8 called vector1? I've read through a lot of material, and even found a site that indicate how you would create the vector...as indicated above, but no information on HOW to actually use it.
typedef is used extensively in C to refer to struct variables without specifying the struct prefix, for example if I had:
struct vector {
double x;
double y;
double z;
};
than to initialize it I'd have to do:
struct vector vector1;
vector1.x = 1.11;
vector1.y = 1.22;
vector1.z = 1.33;
But if I used a typedef in the declaration:
typedef struct vector {
double x;
double y;
double z;
} vector_type;
than I could simplify this initialization like so (note the struct prefix is not needed now):
vector_type vector1;
vector1.x = 1.11;
vector1.y = 1.22;
vector1.z = 1.33;
Of course, I could still use the full struct vector initialization in this case as well
So in your case:
#include <stdio.h>
typedef struct crt8 {
double x;
double y;
double z;
} CART8;
int main(int argc, char** argv)
{
CART8 vector1;
vector1.x = 2.526;
vector1.y = 3.416;
vector1.z = 4.32;
printf("%f %f %f\n", vector1.x, vector1.y, vector1.z);
}
Alternatively, you can always resort to the original struct definition:
#include <stdio.h>
typedef struct crt8 {
double x;
double y;
double z;
} CART8;
int main(int argc, char** argv)
{
struct crt8 x;
x.x = 2.341;
x.y = 3.43;
x.z = 4.521;
printf("%f %f %f\n", x.x, x.y, x.z);
}
You wrote:
typedef struct crt8 {
double x;
double y;
double z;
} CART8;
This defined a new 'type'. The 'typename' is struct crt8 or the alias you defined CART8. This is how you instantiate an object from that type in C:
struct crt8 myVector;
or you can use the alias 'CART8' that you've defined:
CART8 myVector;
Either way, this is how you populate the 'members' of your object:
CART8 x; // Creation of object
x.x = 100;
x.y = 101;
x.z = 102;
Here is a demonstrative program that shows various ways how objects of the structure can be created, initialized, and used.
#include <stdio.h>
#include <math.h>
typedef struct crt8 {
double x;
double y;
double z; } CART8;
int main( void )
{
CART8 vector1 = { 1.1, 2.2, 3.3 };
CART8 vector2 = { .x = 1.1, .y = 2.2, .z = 3.3 };
CART8 vector3;
vector3.x = 1.1;
vector3.y = 2.2;
vector3.z = 3.3;
CART8 vector4 = vector1;
CART8 vector5 = { vector1.x + vector2.z, vector1.y + vector2.y, vector1.z + vector2.x };
printf( "vector5 = { %lf, %lf, %lf }\n", vector5.x, vector5.y, vector5.z );
printf( "Magnitude = %lf", sqrt( pow( vector1.x, 2 ) + pow( vector1.y, 2 ) + pow( vector1.z, 2 ) ) );
return 0;
}
The output is
vector5 = { 4.400000, 4.400000, 4.400000 }
Magnitude = 4.115823
I am having a hard here and could use some help (I have been at this for hours and am getting no where...).
OK, so my problem is that I can't figure out how to make a Function that uses a typedef to return a simplified fraction. In other words I want to use Euclidean method to get GCD like this:
int gcd(int a, int b)
{
int rem;
if ((rem = a % b) == 0) {
return b;
}
else {
return gcd(b, rem);
}
}
Then simply with something like this:
int result = gcd(num, den);
int simple_num = num / result;
int simple_den = den / result;
printf("%d / %d", simple_num, simple_den);
But, I am trying to make it with a typedef called fraction and use one function that will return my simplified numerator and denominator.
typedef struct
{
int numerator;
int denominator;
} Fraction;
Fraction simplify(Fraction myFraction)
{
return myFraction;
}
Anyone know how this could be done?
This should work:
Fraction simplify(Fraction myFraction)
{
int result = gcd(myFraction.numerator, myFraction.denominator);
int simple_num = num / result;
int simple_den = den / result;
Fraction newFraction = {simple_num, simple_den};
return newFraction;
}
This question already has answers here:
Compile error: with request not something structure or union error
(2 answers)
Closed 8 years ago.
I'm having trouble with my code. My program is a program to simplify fractions. So my problem is this:
I declare the structure Fraction. And then I declare structure Fraction f in my main function.
But when I try to use any member of the structure fraction (i.e. f.num, f.den) it says it's not a member of a structure or union. I have like 10 errors all saying the same thing for my program.
The error (verbatim): error: request for member "num" in something not a structure of union
#include <stio.h>
struct Fraction{
int num;
int den;
int lownum;//lownum = lowest numerator.
int lowden;//lowden = lowest denominator
int error;
};
void enter(struct Fraction *f);
void simplify(struct Fraction *f);
void display(const struct Fraction *f);
int main(void){
struct Fraction f;
printf("Fraction Simplifier\n");
printf("===================\n");
enter(&f);
simplify(&f);
display(&f);
}
void enter(struct Fraction *f){
printf("Please enter numerator : \n");
scanf("%d", &f.num);
printf("please enter denominator : \n");
scanf("%d", &f.den);
printf("%d %d", f.num, f.den);
}
void simplify(struct Fraction *f){
int a;
int b;
int c;
int negative; //is fraction positive?
a = f.num;
b = f.den;
if (a/b < 0){
negative = 1;
}
if(b == 0){
f.error = 1;
}
if(a < 0){
a = a * -1;
}
if(b < 0){
b = b * -1;
}
//euclids method
if(a < b){
c = a;
a = b;
b = c;
}
while(b != 0){
c = a % b;
a = b;
b = c;
}
f.lownum = f.num / a;
f.lowden = f.den / a;
if(negative = 1){
f.lownum = f.lownum * -1;
}
}
void display (const struct Fraction *f){
if (f.error != 1){
printf("%d / %d", f.lownum, f.lowden);
}else{
printf("error");
}
}
In
void simplify(struct Fraction *f)
f is a pointer to struct Fraction. Therefore, instead of
a = f.num;
you have to write
a = (*f).num;
which can be shortened to the equivalent notation:
a = f->num;
The same applies to all other references to struct Fraction *f in your functions.
You use a pointer (struct Fraction *f). So you have to acces members with the -> operator:
f->num
I am very new to c programming. I have written the fallowing code
float value; //golbal variable
unsigned int data; //golbal variable
void Maxphase(void)
{
float MAX = 0.0;
unsigned int i,index;
for (i=0;i<=360;i++)
{
phaseset(i);
data = readvalue();
value = voltage(data);
if(value>MAX) //find max value
{
MAX = value; //max voltage
index = i;
}
}
printf("Max Voltage Value:%f\r\n", MAX);
printf("Related index Value:%d\r\n", index);
}
the above code working perfectly and printing maximum voltage and index. I want return both values "Max" and "index" from this function and I have to save Max value in one variable and index value in other variable like.
void runCom(void){
c=getchar();
switch(c){
case '1':
Maxphase();
Vin= (I want to store MAX value of that function)
p1= ( I want to store Index of that function)
break;
default:
break;
}
}
Actually I want call that function and it has to return two variables MAX and index value, thus I want to store those two values in different variables.
I know function can't return two values.
I have searched, i found it is possible with a struct or make the function to handle the arguments with pointers. I tried with struct as shown below.
typedef struct {
float v;
unsigned int p;
}volphase;
I have declared this struct in header file. I am including this header file in all files where i am calling.
volphase Maxphase()
{
volphase vp;
float MAX = 0.0;
unsigned int i,index;
for (i=0;i<=360;i++)
{
phaseset(i);
data = readvalue();
value = voltage(data);
if(value>MAX) //find max value
{
MAX = value; //max voltage
index = i;
}
}
vp.v=MAX;
vp.p=index;
return vp;
}
This is written in "bvr.c" file.
But I am thinking how to call this "struct" in case'1'(main.c) and how to store vp.v in one variable and vp.p in another variable.
Please suggest me if any thing wrong in writing struct. or any other easiest way that will return two values.
please help me how to do this.
Returning a struct from the function is the least common of the two ways to return multiple values. Using pointers is more common:
void Maxphase(float *max, unsigned int *index)
{
*max = 0.0;
float value;
unsigned int i, data;
for (i=0;i<=360;i++)
{
phaseset(i);
data = readvalue();
value = voltage(mux1);
if(value > *max) //find max value
{
*max = value; //max voltage
*index = i;
}
}
printf("Max Voltage Value:%f\r\n", *max);
printf("Related index Value:%d\r\n", *index);
}
Here is how you call this function:
int main() {
float max;
unsigned idx;
Maxphase(&max, &idx);
printf("Max Voltage Value:%f\r\n", max);
printf("Related index Value:%d\r\n", idx);
return 0;
}
I would return the phase from the function - the function name is MaxPhase, which implies that it returns a value of maximum phase. The index at which it found the max can be returned using a pointer.
Note that the data value is unused and mux1 is undefined. Note also that I used idx instead of index as the latter is sometimes already defined in standard libraries (although perhaps not in yours).
float MaxPhase(int * maxindex)
{
float max = 0.0;
int idx = -1;
for (int i=0; i<=360; i++) {
phaseset(i);
unsigned int data = readvalue();
float value = voltage(mux1);
if (value > max) {
max = value;
idx = i;
}
}
*maxindex = idx;
return max;
}
void caller(void)
{
int idx = 0;
float phase = MaxPhase(&idx);
printf("Max Voltage Value:%f\n", phase);
printf("Related index Value:%d\n", idx);
...
}
#include <stdio.h>
struct lol
{
float val;
int ind;
};
void olol(struct lol *lol1)
{
lol1->val = 5;
lol1->ind = 3;
}
int main(void) {
struct lol mylol = {0,0};
olol(&mylol);
printf("lololol %f %d \n", mylol.val, mylol.ind);
printf("lol\n");
return 0;
}
You can solve this in several different ways:
1.define a struct containing the two values and returning that struct.
#include <stdlib.h>
struct Values {
int v1, v2;
};
struct Values *get2Values () {
struct Values *x=(struct Values*)malloc (sizeof (struct Values));
x->v1=1;
x->v2=1231;
return x;
}
and voila, you have a memory leak if you dont treat the returned value right...
2.use pointers as parameters where the values will go, e.g.
Pointers:
void get2Values (int *v1, int *v2) {
*v1=1;
*v2=131231;
}
int main () {
int a1, a2;
get2Values (&a1, &a2);
}
Good luck!