Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game. |
Notices |
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
Are you new to LinuxQuestions.org? Visit the following links:
Site Howto |
Site FAQ |
Sitemap |
Register Now
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
|
 |
|
03-19-2011, 07:43 PM
|
#1
|
Member
Registered: Jan 2010
Location: Maryland
Distribution: Ubuntu
Posts: 58
Rep:
|
C programming
Hi, i'm writing a program for my homework, like most of you must know. This is the code I have(it's not complete yet)
Code:
#include<stdio.h>
double bestfit(double equation)
{
double x, n, y, x2, xy, m , b, meanx, meany, meanxy, meanx2;
meanx = x/n;
meany = y/n;
meanxy = xy/n;
meanx2 = x2/n;
b = ((meanx2 * meany)-(meanx*meanxy))/(meanx2 - (meanx*meanx));
m = (meanxy - (meanx * meany))/(meanx2 - (meanx*meanx));
return (m*x) + b;
}
int main()
{
double x = 0, y = 0, m, b, i, n, meanx, meany, meanx2, meanxy, equation;
printf("how many points do you want to plot? ");
scanf("%lf", &n);
for(i = 1; i <= n; i++){
printf("enter value for x: ");
scanf("%lf", &x);
x +=x;
if(x <= -10000)
break;
printf("enter value for y: ");
scanf("%lf", &y);
y += y;
m = (meanxy - (meanx*meany))/(meanx2 - (meanx*meanx));
b = ((meanx2 * meany)-(meanx*meanxy))/(meanx2 - (meanx*meanx));
equation = bestfit(equation);
}
printf("%lf\n", m);
printf("%lf\n", b);
printf(" the values for m and b for your data are: %lf\n, and: ", equation);
return 0;
}
I want to know is how to display the value of m and b inside the main function. How do i call those values from the function I made above so I can output them on the screen besides rewriting it like i did above, or do I have to make another function for them? can someone EXPLAIN! how to do that? 
the program up there might be wrong to you, but it looks right to me 'cause i'm a
I want some advice
Last edited by j360; 03-19-2011 at 07:45 PM.
|
|
|
Click here to see the post LQ members have rated as the most helpful post in this thread.
|
03-19-2011, 08:06 PM
|
#2
|
Senior Member
Registered: Sep 2009
Location: Washington U.S.
Distribution: M$ Windows / Debian / Ubuntu / DSL / many others
Posts: 2,339
|
Make m and b global.
|
|
|
03-19-2011, 08:11 PM
|
#3
|
Member
Registered: Jan 2010
Location: Maryland
Distribution: Ubuntu
Posts: 58
Original Poster
Rep:
|
sounds like a good idea, what a  I am, I never thought about it
|
|
|
03-19-2011, 08:52 PM
|
#4
|
Member
Registered: Jan 2010
Location: Maryland
Distribution: Ubuntu
Posts: 58
Original Poster
Rep:
|
is there any way I can have two main() functions in the same program like in C++
|
|
|
03-19-2011, 10:45 PM
|
#5
|
Senior Member
Registered: Dec 2008
Posts: 4,732
|
Quote:
Originally Posted by j360
I want to know is how to display the value of m and b inside the main function.
|
Instead of returning a single value from that function, you can put ALL the values in an ARRAY and the return the array, which can be accessed in main.
and you can't have two main() neither in C nor in C++.
|
|
|
03-20-2011, 12:21 AM
|
#6
|
LQ 5k Club
Registered: Aug 2005
Distribution: OpenSuse, Fedora, Redhat, Debian
Posts: 5,399
|
You can pass the arguments as pointers to variables defined by the caller. You can return a pointer to an array or structure that is statically allocated by the called function. You can allocate an array or structure, pass it by reference and return a reference to it. You can have the caller allocate space for a structure (malloc()/calloc()) and return a pointer to it (but be careful about making sure it gets free()ed appropriately). As others have mentioned, they could be global variables (my last choice).
--- rod.
|
|
|
03-20-2011, 12:56 PM
|
#7
|
Senior Member
Registered: Sep 2009
Location: Washington U.S.
Distribution: M$ Windows / Debian / Ubuntu / DSL / many others
Posts: 2,339
|
But global variables are the easiest choice. Maybe not a good practice to use alot but definitely the easiest.
And you can only have one main(). Infact you can only have one function of a particular name.
|
|
|
03-20-2011, 02:04 PM
|
#8
|
LQ Guru
Registered: Dec 2007
Distribution: Centos
Posts: 5,286
|
Quote:
Originally Posted by j360
I want to know is how to display the value of m and b inside the main function.
|
What you should want to know is how to pass a set of related information into or out of a function.
You do that by defining a structure type, instantiating an instance of the structure at the outermost level needing it and passing a pointer to that structure to inner levels needing it.
I hate giving this much of the answer as code, but my prior attempts at giving you concepts have failed. I hope this is the right amount of code that will encourage you to think rather than just copy.
First we define two structure types, one for the data to be passed in and one for the data to be passed out. This is done outside and before any functions, so all functions share these definitions.
Code:
typedef struct data_summary {
int n;
double total_x;
double total_x2;
double total_xy;
double total_y; } data_summary;
typedef struct line {
double m;
double b; } line;
Then the signature of the function indicates that it takes both the output structure and the input structure as input pointers. That may seem a strange concept (both output and input passed as input), but that is how it is done:
Code:
void best_fit( line* result, data_summary* d )
Then inside that function, you use input values with structure pointer syntax: Notice how total_x and n are accessed from the structure:
Code:
double meanx = d->total_x / d->n;
Later in the function you store results into the output structure in a similar way:
Code:
result->m = (meanxy - (meanx * meany))/(meanx2 - (meanx*meanx));
Inside the main() function, you define storage space for one instance of each of those structures, such as:
Code:
int main() {
data_summary d_storage;
line equation_storage;
...
Then you make a pointer variable for that structure to allow main() to use the same syntax for members as other functions use:
Code:
data_summary* d = &d_storage;
line* equation = &equation_storage;
Expert programmers usually don't do that, but if you don't you must remember that structures and the members are accessed with a different syntax in the function defining them than in functions getting them via pointer. For a beginner, it is less confusing to use the pointer everywhere.
Then you want to initialize any structure members that need initial values, such as
Code:
d->total_x = 0.0;
d->total_x2 = 0.0;
d->total_xy = 0.0;
d->total_y = 0.0;
Then you may directly use structure members in the main function, such as:
Code:
printf("how many points do you want to plot? ");
scanf("%d", &d->n);
Notice I had decided n made more sense as an int, so I fixed the scanf to be consistent with that choice.
Also
Code:
d->total_x += x;
d->total_x2 += x*x;
etc.
Then you pass both structure pointers to the function
Code:
best_fit( equation, d );
finally you can use the results equation->b and equation->m
Last edited by johnsfine; 03-20-2011 at 02:07 PM.
|
|
2 members found this post helpful.
|
03-20-2011, 02:13 PM
|
#9
|
LQ 5k Club
Registered: Aug 2005
Distribution: OpenSuse, Fedora, Redhat, Debian
Posts: 5,399
|
Quote:
Originally Posted by smeezekitty
But global variables are the easiest choice. Maybe not a good practice to use alot but definitely the easiest.
And you can only have one main(). Infact you can only have one function of a particular name.
|
By extension of this logic, all variables should be global. Sorry, not buying that. I think johnsfine said it best when he said
Quote:
You do that by defining a structure type, instantiating an instance of the structure at the outermost level needing it and passing a pointer to that structure to inner levels needing it.
|
Only the code that needs to see some data should be able to see that data. That you can have only one instance of any symbol (variable or function) is exactly the problem that correct use of visibility and scope rules solves.
--- rod.
|
|
|
03-20-2011, 02:16 PM
|
#10
|
Senior Member
Registered: Sep 2009
Location: Washington U.S.
Distribution: M$ Windows / Debian / Ubuntu / DSL / many others
Posts: 2,339
|
Quote:
Originally Posted by theNbomr
By extension of this logic, all variables should be global. Sorry, not buying that.
|
Obviously you failed to read or interpret this correctly.
Not all variables should be global because most variable do not need to be accessed at global scope.
|
|
|
03-20-2011, 02:24 PM
|
#11
|
LQ Guru
Registered: Dec 2007
Distribution: Centos
Posts: 5,286
|
Note to j360: Please focus on post #8, not this post
Quote:
Originally Posted by smeezekitty
Obviously you failed to read or interpret this correctly.
|
He obviously did not fail to read or interpret it correctly.
You are not in disagreement about facts. You are in disagreement about how to teach beginners.
When do you give beginners a simpler method that will become wrong as they advance, justifying that by the fact that too many advanced concepts at once will be overwhelming?
When do you reject certain simpler methods, because they train the wrong way of looking at problems and are harder to unlearn than learning to do it right in the first place.
This is a philosophy of teaching question, not a right/wrong question about C programming.
Issue by issue, I personally might take either side of that question. I strongly believe in teaching complex topics in manageable bits, not every detail the professional way from the start.
On misuse of globals (today at least), I lean the other way. Better to avoid learning what you will need to unlearn.
Quote:
By extension of this logic, all variables should be global.
|
When you first start, globals are easiest. For any variable accessed by more than one function, a global is clearly easiest. For any variable accessed by only one function a global is easier for a beginner than figuring out that it is only accessed by one function and making it different from variables accessed by more than one function.
But what is easiest for each variable turns out to be impossible when applied to all variables and incredibly ugly and unmaintainable when applied to many variables.
When you write a best_fit function that will be used exactly once in a simple program, it is easiest to make every input to the function a global. By a much wider margin, it is easiest to make every output from the function a global.
But by the time you are writing a best_fit function at all, even if that first example is used exactly once, you are not supposed to be learning how to write functions that are used exactly once. You are already learning how to write general purpose functions. Those do not return their outputs in globals.
Last edited by johnsfine; 03-20-2011 at 03:44 PM.
|
|
|
03-20-2011, 03:00 PM
|
#12
|
LQ 5k Club
Registered: Sep 2009
Posts: 6,443
|
I agree about not using globals. Return a struct or pass pointers instead.
An example of the pointer technique:
Code:
// When a variable is defined with a '*', it means it holds the memory
// address in which a piece of data is stored, not the data itself.
void test_function(int *a, int *b)
{
*a += 2; // The '*' operator means "get the item stored in address"
*b += 3;
}
int main()
{
int a = 1;
int b = 3;
printf("a: %d; b: %d\n", a, b);
test_function(&a, &b); // the '&' operator means "get the memory address in which this is stored"
printf("a: %d; b: %d\n", a, b);
return 0;
}
Here, we pass a pointers the the variables in main() to test_function. test_function() can now access the copies stored in main() via the pointers.
Last edited by MTK358; 03-20-2011 at 03:02 PM.
|
|
|
03-20-2011, 03:16 PM
|
#13
|
Senior Member
Registered: Sep 2009
Location: Washington U.S.
Distribution: M$ Windows / Debian / Ubuntu / DSL / many others
Posts: 2,339
|
Quote:
When you first start, globals are easiest. For any variable accessed by more than one function, a global is clearly easiest. For any variable accessed by only one function a global is easier for a beginner than figuring out that it is only accessed by one function and making it different from variables accessed by more than one function.
But what is easiest for each variable turns out to be impossible when applied to all variables and incredibly ugly and unmaintainable when applied to many variables.
When you write a best_fit function that will be used exactly once in a simple program, it is easiest to make every input to the function a global. By a much wider margin, it is easiest to make every output from the function a global.
But by the time you are writing a best_fit function at all, even if that first example is used exactly once, you are not supposed to be learning how to write functions that are used exactly once. You are already learning how to write general purpose functions. Those do not return their outputs in globals.
|
Returning a structure (PITA) is no more portable then creating a global variable structure since it still needs a definition.
Also, who said anything about global inputs?
|
|
|
03-20-2011, 03:18 PM
|
#14
|
LQ Guru
Registered: Dec 2007
Distribution: Centos
Posts: 5,286
|
Note to j360: Please focus on post #8
Most of the discussion after that has been meta discussion about how to teach beginners and/or about programming style. It has not been info directly useful to you.
That is especially true of this post #14.
Quote:
Originally Posted by MTK358
I agree about not using globals. Return a struct or pass pointers instead.
|
There are lots of ways to accomplish the basic task of returning multiple values from a function, such as:
1) Globals: Almost always bad.
2) Pass in a pointer to an output struct: My choice in this case.
3) Return a pointer to a struct dynamically allocated within the function: My usual choice in actual programming. Not a good choice for a beginner nor a good choice in most situations (my programming tasks are not typical programming tasks).
4) Return a pointer to a static struct in the function. Generally a bad idea. An expert might do this occasionally and carefully.
5) Return a struct by value. That is one of the simplest choices, but I think it would get a beginner into bad habits.
6) Pass in individual pointers for individual return values. That is probably the common solution.
7) If the types are consistent, you might use an array instead of a struct (see post #5). I would want a lot more consistency than just type among the outputs before I'd consider this choice. Then it has sub choices similar to 2, 3 and 4 above. (C cannot pass or return an array by value, so no choice similar to 5).
You seem to have suggested 5 and you demonstrated 6. In a slightly different example, I'd agree with you about passing individual pointers. It is a judgment call, but in such cases I ask myself what ties this set of values together. Are these outputs (m and b) tied together mainly because they are both computed and returned by best_fit or are they more fundamentally tied together? In this case the pair of outputs is much more fundamentally tied together than simply being outputs of best_fit and the set of inputs (n, total_x, total_x2, etc.) is more fundamentally tied together than just as inputs to best_fit.
So passing struct pointers for each of those sets of values is the right approach, not just a selection from a large set of possible approaches.
A beginner doesn't have the experience to make best choices. But that experience level will be even harder to reach if the beginner isn't shown best choices in examples along the way.
Quote:
Originally Posted by smeezekitty
Returning a structure (PITA) is no more portable then creating a global variable structure since it still needs a definition.
|
The global struct definition is an abstraction one level above an instance of data, just as a global function definition is an abstraction at that same level. I don't think anyone in this thread disagreed with having best_fit defined at global scope.
The bigger your project is, the uglier globals gets. Globals for data instances such as function return values get too ugly too fast to belong in even the trivial example of this thread. Even global abstractions, such as struct definitions and function definitions eventually become too ugly for routine use in giant projects. But global abstractions are OK well beyond beginner C programming and global abstractions are hard to avoid in C programming. I prefer C++, in small part because it is better at organizing those abstractions.
But to answer your point, just notice the fundamental difference between a global data instance and a global abstraction.
Quote:
Also, who said anything about global inputs?
|
Rod and I both extrapolated (I think correctly) from your statement:
Quote:
But global variables are the easiest choice.
|
Also notice the quoted original program failed to pass the inputs to the function. The OP asked about the problem returning results from the function, but we can see help is also required for inputs.
We know you only meant outputs when you said "global variables are easiest". But your logic applies equally well (in our view equally badly) to inputs.
Last edited by johnsfine; 03-20-2011 at 04:12 PM.
|
|
|
03-20-2011, 04:06 PM
|
#15
|
LQ 5k Club
Registered: Sep 2009
Posts: 6,443
|
Quote:
Originally Posted by smeezekitty
Returning a structure (PITA) is no more portable then creating a global variable
|
It's not about portability, it's about readability, modularity, and good practice.
|
|
|
All times are GMT -5. The time now is 02:41 AM.
|
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.
|
Latest Threads
LQ News
|
|