Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
How can i divide and multiplicate 2 variables in C with Pointers?
I tried this:
int multiplicate(int *x,int *y)
{
*x**y;
}
int divide(int *x,int *y)
{
*x/*y;
}
You are missing the return statement:
int multiplicate(int* x, int* y)
{
return (*x) * (*y);
}
int divide(int *x,int *y)
{
return (*x) / (*y);
}
Use *x/(*y) instead. Else it's interpreted as a multiline comment. And you forgot return
Since the indirection operator has higher precedence that multiplication operator, parenthesis are not needed.
Simply adding some whitespace will do:
int multiplicate(int *x,int *y)
{
return *x * *y;
}
int divide(int *x,int *y)
{
return *x / *y;
}
Pointer Division possible?
You do not try to devide pointers here, but as using the dereferencing *-operator, the values the pointers are pointing to are use.
However, as all examples given so far fully miss essential error checking, I propose the following approaches:
int multiply(int * pr, int * px, int * py)
{
int result = 0; /* Be optimistic. */
if (NULL == pr || NULL == px || NULL == py)
{
errno = EINVAL;
result = -1;
}
else
{
*pr = *px * *py;
}
return result;
}
int devide(int * pr, int * px, int * py)
{
int result = 0; /* Be optimistic. */
if (NULL == pr || NULL == px || NULL == py)
{
errno = EINVAL;
result = -1;
}
elseif (0 = *py) /* Division by zero is not defined. */
{
errno = EDOM;
result = -1;
}
else
{
*pr = *px / *py;
}
return result;
}
Call those functions like this:
#include <stdio.h>
#include <errno.h>
/* The two functions above go here. */
int main(int argc, char ** argv)
{
int result = EXIT_SUCCESS;
if (2 > argc)
{
fprintf("Missing or invalid arguments.\n");
printf("Usage: %s x y\n", argv[0]);
result = EXIT_FAILURE;
}
if (EXIT_SUCCESS == result)
{
int x = atoi(argv[1]); /* Better use strtol here. */
int y = atoi(argv[2]); /* Better use strtol here. */
printf("Got x = %d and y = %d.\n", x, y);
{
int r;
if (-1 == multiply(&r, &x, &y)
{
perror("multiply() failed");
}
else
{
printf("%d * %d = %d\n", x, y, r);
}
}
{
int r;
if (-1 == multiply(&r, &x, &y)
{
perror("devide() failed");
}
else
{
printf("%d / %d = %d\n", x, y, r);
}
}
}
return result;
}
Finally a more sane approach would be to use pointers only where needed.
A possible approch modifying the above examples would look like this:
int multiply(int * pr, int x, int y)
{
int result = 0; /* Be optimistic. */
if (NULL == pr)
{
errno = EINVAL;
result = -1;
}
else
{
*pr = x * y;
}
return result;
}
int devide(int * pr, int x, int y)
{
int result = 0; /* Be optimistic. */
if (NULL == pr)
{
errno = EINVAL;
result = -1;
}
elseif (0 = y) /* Division by zero is not defined. */
{
errno = EDOM;
result = -1;
}
else
{
*pr = x / y;
}
return result;
}
Call those functions like this:
#include <stdio.h>
#include <errno.h>
/* The two functions above go here. */
int main(int argc, char ** argv)
{
int result = EXIT_SUCCESS;
if (2 > argc)
{
fprintf("Missing or invalid arguments.\n");
printf("Usage: %s x y\n", argv[0]);
result = EXIT_FAILURE;
}
if (EXIT_SUCCESS == result)
{
int x = atoi(argv[1]); /* Better use strtol here. */
int y = atoi(argv[2]); /* Better use strtol here. */
printf("Got x = %d and y = %d.\n", x, y);
{
int r;
if (-1 == multiply(&r, x, y)
{
perror("multiply() failed");
}
else
{
printf("%d * %d = %d\n", x, y, r);
}
}
{
int r;
if (-1 == multiply(&r, x, y)
{
perror("devide() failed");
}
else
{
printf("%d / %d = %d\n", x, y, r);
}
}
}
return result;
}
Related
#include <stdio.h>
int FAC(int a)
{
if (a >= 1, a--)
{
return a + 1 * a;
FAC(a);
}
}
int main()
{
int a = 0;
int ret = 0;
scanf("%d", &a);
ret = FAC(a);
printf("%d\n", ret);
}
if I input 5 the outcome is 8
But in the first function should't it be
5>=1 5-1 return 5*4 4>=1...
First of all, you're returning a value before you're using recursion. The return keyword takes effect immediately, so all statements following this won't be executed.
Also, your factorial function does not actually calculate the factorial of a.
Examples for factorial functions:
Recursive
int factorial(int n) {
if(n > 0) {
return n * factorial(n - 1); // n! = n * (n-1) * (n-2) * ... * 1
} else {
return 1;
}
}
Iterative
// Does exactly the same, just an iterative function
int factorial(int n) {
int fac = 1;
for(; n > 0; n--) {
fac *= n;
}
return fac;
}
Your factorial function (FAC) should ideally be something like:
unsigned int FAC(unsigned int a)
{
// base condition - break out of recursion
if (a <= 1)
return 1;
return a * FAC(a - 1);
}
unsigned int restricts range of argument to be in [0, UINT_MAX].
Do note that FAC returns a unsigned int, so you may be able to provide argument value up to 12, else there will be an overflow and you can see weird output.
BTW, UINT_MAX is defined in limits.h
#include <stdio.h>
int FAC(int a)
{
if (a < 0) {
return -1;
} else {
if (a == 0) {
return 1;
} else {
return (a * FAC(a-1));
}
}
}
int main()
{
int a = 0;
int ret = 0;
scanf("%d", &a);
ret = FAC(a);
if (ret == -1) {
printf("%s\n", "Input was a negative integer.");
} else {
printf("%d\n", ret);
}
}
This question already has answers here:
Input too big for array
(4 answers)
Closed 2 years ago.
When I use sscanf, I found some other variable is changed as well but I don't know why.
My code is:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int add(int a, int b) {
return a + b;
}
int sub(int a, int b) {
return a - b;
}
int mul(int a, int b) {
return a * b;
}
int d(int a, int b) {
return a / b;
}
void manipulate(int* result, int x, int y, int op(int, int)) {
printf("%p\n", result);
*result = op(x, y);
}
int main() {
char line[20];
FILE* f = fopen("sample.txt", "r");
int result = 0;
while (fgets(line, 15, f) != NULL) {
char oper[3];
char valA[3];
char valB[3];
sscanf(&line[0], "%s %s %s", oper, valA, valB);
int x;
int y;
printf("%d\n", result);
if (valA[0] == '%') {
x = result;
y = atoi(valB);
} else if (valB[0] == '%') {
x = atoi(valA);
y = result;
} else {
x = atoi(valA);
y = atoi(valB);
}
printf("%d %d\n", x, y);
if (strcmp(oper, "ADD") == 0) {
manipulate(&result, x, y, &add);
} else if (strcmp(oper, "SUB") == 0) {
manipulate(&result, x, y, &sub);
} else if (strcmp(oper, "MUL") == 0) {
manipulate(&result, x, y, &mul);
} else if (strcmp(oper, "DIV") == 0) {
manipulate(&result, x, y, &d);
}
}
}
I used the debugger to track the value of the variable named result. In the first loop, the result becomes the value I want, but when it entre the second loop and finish the line sscanf, the result becomes 0 again. Could anyone tell me why? Thank you so much :)
Your char arrays are too small, because you didn't account for null terminators. The string ADD requires 4 characters ('A', 'D', 'D', and '\0'), but you're storing it in char oper[3], and writing past the end is Undefined Behavior. In this case, that happens to mean that the '\0' gets stored on top of result, setting it to 0.
I want to do a void factorial function in C that uses pointers. This is my code but it won't run.
#include <stdio.h>
void factorial(int, int*);
int main()
{
int n;
int r = 0;
printf("Enter n : ");
scanf("%d", &n);
if (n < 0)
{
printf("No factorial for negative");
}
else
{
factorial(n , &r);
printf("factorial of %d is %d", n, r);
}
}
void factorial(int n , int *r)
{
if (n == 0 || n == 1)
{
*r= 1;
}
else
{
*r= n* factorial((n-1), r);
}
}
The error I get is in the last line of the code saying : invalid operands of type "int" and "void" to binary operator * , what does that mean and how to fix it?
Well, if factorial() returns void (which is basically , returning nothing) , this line does not make any sense
*result = num * factorial ((num-1), result);
It's because factorial() returns void.
Try:
factorial((num-1), result);
*result= num *(*result);
Instead of that line.
You cannot use return value of a function if it is declared to return void.
If you want to declare function this way then your factorial function can be:
void factorial(int num , int *result)
{
if (num == 0 || num == 1)
{
//*result = 1;
return;
}
else
{
*result *= num;
factorial ((num-1), result);
}
But also in main function you should change int res = 0 into int res = 1.
void Factorial(int *a,int *result){
if (*a == 0 || *a == 1){
return;
}
else{
*result *= *a;
*a -= 1;
Factorial(a,result);
}}
I want to write a power function that prints "Unable to compute o^o" when asked to do so or return the integer result. how can I accomplish this?
My current code prints the error statement as well as the result statement.
My code:
#include <stdio.h>
double power(int base,int n);
int main() {
int no1,no2;
printf("Enter two numbers:\n");
printf("If you want to compute x^y enter x y\n");
scanf("%i%i", &no1, &no2);
printf("The value of %i^%i is %f", no1, no2, power(no1,no2));
return 0;
}
double power(int base, int n) {
double result = 1;
if( n == 0 && base == 0){
printf("Unable to compute 0^0\n");
}
else if( n == 0 && base != 0) {
result = 1;
}
else if( n>0 ){
for(n ; n>0 ; n--) {
result = result*base;
}
}
else if( n<0 ){
int temp = -n;
result = power(base,temp);
result = (float)1.0/result;
}
return result;
}
EDIT: I am actually a novice. I am in the first chapter of K&R where I found a power function. I wanted to improve that thing and found this hurdle. Hence please provide resources if possible so that I understand your answers.
#BartoszMarcinkowski gives you the correct answer, as an alternative (if you can't pass an extra variable) you can return NAN and check the result with isnan().
In computing, NaN, standing for not a number, is a numeric data type
value representing an undefined or unrepresentable value, especially
in floating-point calculations.
#include <stdio.h>
#include <math.h>
double power(int base,int n);
int main(void)
{
double f;
f = power(2, 2);
if (isnan(f)) {
printf("Unable to compute power\n");
} else {
printf("%f\n", f);
}
return 0;
}
double power(int base, int n) {
double result = 1;
if( n == 0 && base == 0){
return NAN;
}
...
return result;
}
It is common for C functions to return 0 on success or error code in case of failure.
#include <stdio.h>
int power(int base,int n, double *result);
int main() {
int no1, no2;
printf("Enter two numbers:\n");
printf("If you want to compute x^y enter x y\n");
scanf("%i%i", &no1, &no2);
double result;
int error = power(no1, no2, &result);
if(error == 0)
printf("The value of %i^%i is %f\n", no1, no2, result);
return 0;
}
int power(int base, int n, double *result) {
*result = 1;
if(n == 0 && base == 0){
printf("Unable to compute 0^0\n");
return 1;
} else if(n == 0 && base != 0) {
*result = 1;
return 0;
} else if(n>0){
for(; n>0 ; n--) {
*result = *result*base;
}
return 0;
} else if(n < 0){
int temp = -n;
power(base,temp, result);
*result = (float) 1.0 / *result;
return 0;
}
return 1;
}
Note : My answer is in reference to the user's post saying that he is
a novice at learning C, so I have assumed that he might not have yet
be comfortable dealing with pointers.
You can have an error flag in your code that tells the main function that an error has occurred.
You can use a global integer, that is common to all functions of your program to inform of errors in code.
After calling the power function, you check whether the error FLAG is set, which means errors have occurred. So you print the error message instead of the result.
What value you should use for showing a error has occurred is arbitrary. In most cases, a non-zero (sometimes negative) value can indicate the specific error. For example:
FLAG = -1 might indicate invalid input
FLAG = -2 might indicate invalid operation
And so on. etc. Here I have chosen FLAG = non-zero value to mean error has occurred.
#include <stdio.h>
double power(int base,int n);
--> char FLAG = 0;
int main() {
int no1,no2;
---- your code ---
double and = power(no1,no2);
--> if (char) {
printf("error : both values cannot be negative);
char = 0;
} else {
printf("The value of %i^%i is %f", no1, no2, ans);
}
return 0;
}
double power(int base, int n) {
---- your code ---
if( n == 0 && base == 0){
printf("Unable to compute 0^0\n");
--> FLAG = -1;
return 0;
}
else if( n == 0 && base != 0) {
result = 1;
}
else ---- your code ---
}
I'm trying to write a program that would convert celcius to fahrenheit and visa-versa. My program is compiling, but it gives me wrong results. I'm been trying to change it by changing pointers, but it wouldnt work. Can anyone please point out to me what is my problem? It seems to me it's in declarations and pointers, but i'm not sure.Thanks!
#include<stdio.h>
float f2c(float f);
float c2f(float c);
int main(void)
{
float cel;
float celcius;
float fahren;
float fah;
char ch;
float number;
scanf("%c %f", &ch, &number);
if(&ch == "-f"){
f2c(number);
celcius=f2c(number);
printf("%f", celcius);
}
else{
c2f(number);
fahren = c2f(number);
printf("%f", fahren);
}
return 0;
}
float f2c(float f)
{
float cel = (f - 32) * 5/9;
return cel;
}
float c2f(float c)
{
float fah = (9 * c/5 + 32);
return fah;
}
if(&ch == "-f") this is the problem.
It should be :
if(ch == 'f')
In addition to the other answers:
You are doing needless calls to the conversion functions and throwing away the results, just before doing the same calls again but with proper handling of the return value:
if(&ch == "-f"){
f2c(number); /* This line does absolutely nothing! */
celcius=f2c(number);
printf("%f", celcius);
}
You are comparing char with a C-string "-f". Use strcmp to compare C-strings.
You may also have declare ch as char array to more than one character which you need here. Because, you can't store "-f" in a single char as you do now.
With the changes:
#include<stdio.h>
float f2c(float f);
float c2f(float c);
int main(void)
{
float cel;
float celcius;
float fahren;
float fah;
char ch[25];
float number;
scanf("%s %f", ch, &number);
if(strcmp(ch,"-f")==0){
f2c(number);
celcius=f2c(number);
printf("%f", celcius);
}
else{
c2f(number);
fahren = c2f(number);
printf("%f", fahren);
}
return 0;
}
float f2c(float f)
{
float cel = (f - 32) * 5/9.0;
return cel;
}
float c2f(float c)
{
float fah = (9 * c/5.0 + 32);
return fah;
}
This is essentially your code, but modified it to read the input as C-string.
Use floating-point arithmetic, not integer arithmetic, because in integer arithmetic, 5/9 is 0. So you could make this change to your code (though float parameters are unusual):
float f2c(float f)
{
return (f - 32.0) * 5.0/9.0;
}
float c2f(float c)
{
return 9.0 * c/5.0 + 32.0;
}
Also as one of the other answers states, the condition (&ch == "-f") is never true.
Here is a complete working example, with error checking.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <errno.h>
#include <assert.h>
static double f2c(double f)
{
return (f - 32.0) * 5.0/9.0;
}
static double c2f(double c)
{
return 9.0 * c/5.0 + 32.0;
}
int main (int argc, char *argv[])
{
int i;
const char *label_f = "Fahrenheit";
const char *label_c = "Celcius";
const char *from, *to;
double (*conversion)(double);
from = label_c;
to = label_f;
conversion = c2f;
for (i=1; i<argc; ++i)
{
if (0 == strcmp(argv[i], "-f"))
{
from = label_f;
to = label_c;
conversion = f2c;
}
else if (0 == strcmp(argv[i], "-c"))
{
from = label_c;
to = label_f;
conversion = c2f;
}
else
{
char *suffix = NULL;
double temp_in;
errno = 0;
temp_in = strtod(argv[i], &suffix);
if (ERANGE == errno)
{
if (HUGE_VAL == temp_in)
{
fprintf(stderr, "%s is too big", argv[i]);
return 1;
}
else
{
assert(-HUGE_VAL == temp_in);
fprintf(stderr, "%s is too small", argv[i]);
return 1;
}
}
else if (errno != 0 && (suffix == argv[i]))
{
/* no conversion was performed. */
fprintf(stderr, "%s is not a number", argv[i]);
return 1;
}
else if (*suffix)
{
fprintf(stderr, "Expected a number but saw '%s'\n", argv[i]);
return 1;
}
else
{
const double temp_out = (*conversion)(temp_in);
printf("%f %s is %f %s.\n", temp_in, from, temp_out, to);
}
}
}
return 0;
}