0

I'm doing some homework where I use only elementary operations. I need to code a function which given a positive number, calculates the whole half of that number.

My problem is at:

int half(int x, int y)
{
    return x == 0 ? y : half(x-1-1, y+1) , x == 1 ? y : half(x-1-1, y+1);
}

I don't know what if exists any operator or something that connects these calculations. On that line of code i tried to use ( , ).

I tried to replace ( , ) by using ( | ) and ( & ). But i had many errors.


#include <stdio.h>

int sum(int x, int y)
{
    return y == 0 ? x : sum(x+1, y-1);
}

int half(int x, int y)
{
    return x == 0 ? y : half(x-1-1, y+1) , x == 1 ? y : half(x-1-1, y+1);
}

int main(void)
{
    int x;
    int y=0;
    scanf("%d", &x);
    int z = half(x, y);
    printf("%d\n", z);
    return 0;
} 

On this code i expect the output of 6/2 to be 3 and 5/2 to be 2.

Note: The function sum although is not doing nothing i cannot remove since the homework says not to remove from the code, perhaps i need to use it.

myradio
  • 1,703
  • 1
  • 15
  • 25
vunax
  • 11
  • 5
  • 1
    If you know about `? :`, then you probably have learned about `if` statements already as well, right? They would be much easier to read and write. – walnut Sep 29 '19 at 22:32
  • @uneven_mark Ye i know about `if` but i still didn't learned yet in class so we can't use it. – vunax Sep 29 '19 at 22:35
  • What's the point of the second argument to `half`? This homework seems convoluted. – S.S. Anne Sep 29 '19 at 22:36
  • @JL2210 The second argument is to calculate odd number like 1, 3, 5, etc... – vunax Sep 29 '19 at 22:39
  • @vunax Usually only one number is involved in calculating a half of a number. – S.S. Anne Sep 29 '19 at 22:40
  • 1
    They're teaching recursion and ternary operator but haven't covered `if`??? – pinkfloydx33 Sep 29 '19 at 23:10
  • the function: `sum()` is never called! Please explain why it is even there. – user3629249 Oct 01 '19 at 05:06
  • the initial value of `x` is determined via the input of a value from the user. What if the user enters -1 (or any other number less than 0) – user3629249 Oct 01 '19 at 05:08
  • regarding: `return x == 0 ? y : half(x-1-1, y+1) , x == 1 ? y : half(x-1-1, y+1);` The comma ',' operator will result in the results of the first part of line being evaluated and discarded, so the actual return value will only depend on the last part of the line – user3629249 Oct 01 '19 at 05:12
  • if you really want to find the 1/2 value of an integer, you can simply use: `return x>>1;` – user3629249 Oct 01 '19 at 05:13

1 Answers1

0

You can just use || to put these together:

int half(int x, int y)
{
    return x == 0 || x == 1 ? y : half(x-1-1, y+1);
}
S.S. Anne
  • 15,171
  • 8
  • 38
  • 76