+ 1

C function to return the multiplication and sum of two variables

The question means that it need to return the two answers by word return, so my answer is wrong... int mul_sum(int x, int y) { mul= x * y; sum= x + y; return 0; }

20th Oct 2018, 9:26 AM
Aisha Ali
Aisha Ali - avatar
3 Respuestas
+ 2
Aisha Ali Your solution DONT return two value... One solution is use a struct and return an instance of it.. Example: struct MulSum{ int mul; int sum; }; void mul_sum(int p){ MulSum ret; ret.mul= p*p; ret.sum= p+p; return ret; } int main(){ int a= 9; MulSum ms= mul_sum(a); printf("sum=%d;\nmul=%d", ms.sum, ms.mul); }
20th Oct 2018, 10:15 AM
KrOW
KrOW - avatar
+ 1
it's not possible to return 2 variable at once, but there is a work around. 1. return an array or object, assign both of the value to an array or object properties then return them 2. pass parameter by pointer or reference, assign the answer to those params
20th Oct 2018, 9:40 AM
Taste
Taste - avatar
0
I tried this and its solved: #include <stdio.h> #include <stdlib.h> void mul_sum(int *p) { int mul= (*p) * (*p); printf("mul= %d\n", mul); int sum= (*p) + (*p); printf("sum= %d", sum); } int main() { int a=9; mul_sum(&a); return 0; }
20th Oct 2018, 9:47 AM
Aisha Ali
Aisha Ali - avatar