So I made a function that returns a value which is the connection (sum) of 2 numbers that the user gives. But everytime I enter these 2 numbers, the result is somehow always 0.
float connection(int num1, int num2, float result)
{
result= num1 + num2;
return (result);
}
int main()
{
int num1= 0;
int num2= 0;
float result= 0.0;
printf("\nChoose the first number you'd like to connect: ");
scanf("%d", &num1);
getchar();
printf("choose the second number you'd like to connect: ");
scanf("%d", &num2);
connection(num1, num2, result);
printf("The result is: %f", result);
}
The problem here is (I believe) that you expect the argument result you pass to the function to change value. That's not how C works, instead all arguments are passed by value and the variable result inside the called function is a local variable which has no connection to the result variable in the calling function. Changing one variable will not affect the other.
Instead use the value the function returns:
result = connection(num1, num2, result);
Of course, this means passing result as an argument is totally meaningless, and you don't even need it in the function:
int connection(int num1, int num2)
{
return num1 + num2;
}
Also note that I changed the return-type, as adding two integers will never result in a floating-point number.
On a side-note to modify the argument means you have to pass it by reference, which is not supported by C. It can be emulated though, by using pointers:
void connection(int num1, int num2, int *result)
{
*result = num1 + num2;
}
Then call it as
int result;
connection(num1, num2, &result);
You are mixing up two possibilities: returning a value and changing a variable by passing it to a method as a reference.
This is how to return a value (in this case, you don't need the result parameter):
float connection(int num1, int num2)
{
float result= num1 + num2;
return result;
}
...
result = connection(num1, num2);
This is how to pass a variable as a reference (in this case you don't need a return value):
void connection(int num1, int num2, float *result)
{
*result= num1 + num2;
}
...
connection(num1, num2, &result);
I think forgot to assign your result back to your variable:
connection(num1, num2, result); // returned value is missed
result = connection(num1, num2, result); // returned value saved
If, instead, you want your function to modify the variable, C is passed by value so you need some pointers:
void connection(int num1, int num2, float *result)
{
*result = num1 + num2;
}
connection(num1, num2, &result);
Simply make your function call pass by reference
#include<stdio.h>
float connection(int *num1, int *num2, float *result)
{
*result= *num1 + *num2;
return (*result);
}
int main()
{
int num1= 0;
int num2= 0;
float result= 0.0;
printf("\nChoose the first number you'd like to connect: ");
scanf("%d", &num1);
getchar();
printf("choose the second number you'd like to connect: ");
scanf("%d", &num2);
connection(&num1, &num2, &result); //Function Called by reference
printf("The result is: %f", result);
}
For further details on function calls Read It
Related
#include <stdio.h>
void gcdFinder(int num1, int num2, int *result);
int main()
{
int n1, n2, result;
printf("Enter 2 numbers: \n");
scanf("%d %d", &n1, &n2);
gcdFinder(n1, n2, &result);
printf("rGcd2(): %d\n", result);
return 0;
}
void gcdFinder(int num1, int num2, int *result)
{
printf("Initial : %d %d \n",num1,num2);
*result=num1;
if(num2 ==0 ){
return;
}else{
gcdFinder(num2,(num1%num2),&result);
}
}
I am trying to find the GCD the 2 inputs and storing the result into the result variable. However my code does not seem to work as it only stores one time.
As the output suggest my final value for num1 should be 1 however it is not stored and it remains as 4.
In the function gcdFinder change
gcdFinder(num2,(num1%num2),&result);
to
gcdFinder(num2,(num1%num2), result);
^
No & as result is already a pointer here
Notice:
In main it's correct to use &result because result in main is an int
I am trying to make a program that scans 3 ints and then passes them through a function that sort them by this way- the biggest number will be at 'num3', the second will be at 'num2' and the lowest one will be at 'num1' but for some reason the program crashes when it gets to the sort function.
#include <stdio.h>
#include <stdlib.h>
void swap(int* a, int* b);
void changer(int* num1, int* num2, int* num3);
int main()
{
int num1 = 0;
int num2 = 0;
int num3 = 0;
printf("Please enter your value for 'num1': ");
scanf("%d", &num1);
getchar();
printf("Please enter your value for 'num2': ");
scanf("%d", &num2);
getchar();
printf("Please enter your value for 'num3': ");
scanf("%d", &num3);
printf("\nYour nums before- \n");
printf("num1 == %d\n", num1);
printf("num2 == %d\n", num2);
printf("num3 == %d\n", num3);
changer(&num1, &num2, &num3);
printf("\nYour nums after- \n");
printf("num1 == %d\n", num1);
printf("num2 == %d\n", num2);
printf("num3 == %d\n", num3);
system("PAUSE");
return 0;
}
void changer(int* num1, int* num2, int* num3)
{
if (*num1 > *num3)
{
swap(*num3, *num1);
}
else if (*num1 > *num2)
{
swap(*num1, *num2);
}
if (*num2 > *num3)
{
swap(*num3, *num2);
}
}
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
You should not dereference the pointers when you pass them to swap() since it takes int * and you would be passing int thus causing undefined behavior and in your case a crash. The compiler should warn about incompatible parameters.
Change every occurrence of
swap(*num1, *num2);
/* ^ ^ remove these */
with
swap(num1, num2);
swap(int*, int*) expects the integer pointer to be passed in, assume the value of num1 = 0 and num2 = 2 and when you pass these values to swap(), by dereferencing you are invoking like this swap(0, 2) or on 32 bit system
swap(0x00000000, 0x00000002)
Inside swap(int* a, int* b) you dereference the memory location 0x00000000 (not the memory pointed to by a) at the line,
int temp = *a;
and then you dereference 0x00000002 b at this line and trying to assign it to 0x00000000 (by dereferencing *a)
*a = *b;
You are generating
Memory access violation condition.
which is causing the crash. Summarizing, please do not ignore compiler warnings. Compiler raises warning on the line where you are making swap() calls.
'int *' differs in levels of indirection from 'int'
Both functions take integer pointers (i.e., memory addresses of integers) as arguments. So, the values of the arguments a, b, num1, num2, and num3 must ALWAYS be memory addresses of integers. In the function changer, values of the variables num1, num2, and num3 are ALREADY memory addresses. When you write *num1, value of *num1 is integer but not the memory address of an integer. So, you need to call the function swap as follows:
swap(num3, num1);
swap(num1, num2);
swap(num3, num2);
Is there any other way to return a value to main function using void functions. I don't want to use the following way because I want to ask user to enters some values in main function and then check if those values are correct in the void function.
#include <stdio.h>
void fun_1(int *num1, int *num2) {
printf("Enter both numbers: ");
scanf("%d", num1);
scanf("%d", num2);
}
int main(void) {
int num1, num2, total;
fun_1(&num1, &num2);
total = num1 + num2;
printf("%d \n", total);
}
In this code we ask user to enter values in void function, but I would like to ask user to enter values in main!
There is another way to make use of global variables, but as your program grows more complex, it will probably create more hassles for you then it is worth.
If you use global variables to store your inputs inside the sub-function, then you can directly access them in your main() function to get the values. You won't be needing a return from your sub-function.
Having said that, it would be better to change the function return type (maybe returning a struct containing the user-supplied values, if you more than one value to be returned) to match your requirements.
If you want to read the values in main but check them (ex. make sure both are positive) in another function, you can do this:
#include <stdio.h>
void check_numbers(int num1, int num2, int *valid) {
if ((num1 > 0) && (num2 > 0)) {
*valid = 1;
} else {
*valid = 0;
}
}
int main(void) {
int num1, num2, total, valid;
printf("Enter both numbers: ");
scanf("%d", num1);
scanf("%d", num2);
check_numbers(num1, num2, &valid);
if (valid) {
total = num1 + num2;
printf("%d \n", total);
} else {
printf("numbers are invalid\n);
}
}
When I run the following code, I always get a floating-point exception. How can I fix it?
#include <stdio.h>
//Global Variables
int num, denom, num1, denom1;
void simplify(int *numerator, int *denominator);
int main () {
//Prompt User as to what program is
printf("Fraction Simplifier\n");
printf("===================\n");
//Ask User for Numerator and Denominator
printf("Numerator: ");
scanf("%d", &num);
printf("Denominator: ");
scanf("%d", &denom);
//Call Function
simplify(&num1, &denom1);
//Display final output
printf("%d / %d = %d / %d", num, denom, num1, denom1);
return 0;
}
//Simplify function
void simplify(int *numerator, int *denominator)
{
num = num1;
denom = denom1;
num1 = num1 / num1;
denom1 = denom1 / num1;
num1 = *numerator;
denom1 = *denominator;
}
It looks as if num1 is never initialized. It will be zero, which will result in a division by zero.
Your simplify function is flawed. Here's what it means when you are calling simplify:
call simplify, passing the address of num1 and denom1
And here's what your code inside of simplify means:
num = num1; /* Assign the value of num1 to num, meaning set num to 0. */
denom = denom1; /* Assign the value of denom1 to denom, meaning set denom to 0. */
num1 = num1 / num1; /* Divide num1 (which is 0) by num1 (which is 0). Error! */
You can simplify your program and make it easier to understand by eliminating your global variables. This will also help you to correct your errors. Here's a rewrite:
#include <stdio.h>
void simplify(int numerator, int denominator, int* newNumerator, int* newDenominator);
int main () {
int num, denom, num1, denom1;
/* Do your input code */
//Call Function
simplify(num, denom, &num1, &denom1);
//Display final output
printf("%d / %d = %d / %d", num, denom, num1, denom1);
return 0;
}
//Simplify function
void simplify(int numerator, int denominator, int* newNumerator, int* newDenominator)
{
int simplifiedNumerator;
int simplifiedDenominator;
/* Calculate your results.. left out your original code, which calculates incorrectly */
/* You will refer to the ints numerator and denominator */
/* Assign your results */
*newNumerator = simplifiedNumerator;
*newDenominator = simplifiedDenominator;
}
Notice that simplify now has four parameters. The first two are the values you want to use in the calculation (we don't need pointers), and the pointers are only used to assign the results to the addresses passed in.
I have a quick question in the program I'm trying to create. I can't seem to figure out how I can carry through the value that someone inputs for my variable of "denom" so that it can be successfully used in the function I've created. Help would be much appreciated.
#include <stdio.h>
//Global Variables
int num, denom;
void simplify(int *numerator, int *denominator);
int main () {
int num1, denom1;
//Prompt User as to what program is
printf("Fraction Simplifier\n");
printf("===================\n");
//Ask User for Numerator and Denominator
printf("Numerator: ");
scanf("%d", &num);
printf("Denominator: ");
scanf("%d", &denom);
//Call Function
simplify(&num1, &denom1);
//Display final output
printf("%d / %d = %d / %d\n", num, denom, num1, denom1);
return 0;
}
//Simplify function
void simplify(int *numerator, int *denominator)
{
int num1, denom1;
num1 = 1;
num = num1;
denom = denom1;
num1 = num1 / num1;
denom1 = denom1 / num1;
*numerator = num1 ;
*denominator = denom1;
}
Your simplify() method doesn't even try to use the passed values.
It boils down to *numerator = 1 and *denominator = is undefined (since denom1 is never initialized). i.e. it sets "out values" to "constants". You probably meant to do something like:
int num1 = *numerator;
int denom1 = *denominator;
In Simplify() function:
*int num1, denom1;
denom = denom1;* (1)
denom1 = denom1 / num1; (2)
*denominator = denom1;* (3)
in (1) denom1 has undefined values. So when you use:
(2)denom1 still has an undefined value
and in (3)
denominator has an undefined value