I am trying to do a simple calculator using C. I have created 4 functions which are doing addition, multiplication, subtraction and divison. However, when I call the functions in the main function, they are not working correctly. The results are always multiplied even if I type "+", "-", "/". What may be the problem here?
Translation of some words to be clear: arti = plus, eksi = minus, carpi = cross, bolum = divide, carpim = multiplication, toplama = addition, cikartma = subtraction, bolme = divison
Thanks :)
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
int carpim(int numOne, int numTwo, int result){
result = numOne * numTwo;
printf("Sonuc: %d", result);
return 0;
}
int toplama(int numOne, int numTwo, int result){
result = numOne + numTwo;
printf("Sonuc: %d", result);
return 0;
}
int cikartma(int numOne, int numTwo, int result){
result = numOne - numTwo;
printf("Sonuc: %d", result);
return 0;
}
int bolme(int numOne, int numTwo, int result){
result = numOne / numTwo;
printf("Sonuc: %d", result);
return 0;
}
int main(){
char islem[0];
char arti[] = "+";
char eksi[] = "-";
char carpi[] = "x";
char bolum[] = "/";
int sayiBir;
int sayiIki;
int sonuc = 0;
printf("(+)\n(-)\n(x)\n(/)\nIstediginiz islemin sembolunu girin:");
scanf("%c", islem);
printf("Ilk sayiyi girin: ");
scanf("%d", &sayiBir);
printf("Ikinci sayiyi girin: ");
scanf("%d", &sayiIki);
if (strcmp(islem, arti)) {
toplama(sayiBir, sayiIki, sonuc);
}
else if (strcmp(islem, carpi)){
carpim(sayiBir, sayiIki, sonuc);
}
else if (strcmp(islem, eksi)){
cikartma(sayiBir, sayiIki, sonuc);
}
else if (strcmp(islem, bolum)){
bolme(sayiBir, sayiIki, sonuc);
}
}
You have two major problems:
The first is that the array islem
is an array of zero elements, it can't hold anything much less a null-terminated string
The second problem is that you read a single character, and attempt to use it as a null-terminated string when you pass it to the strcmp
functions (the str
prefix means it handles null-terminated strings).
To solve these problems, make islem
a single character:
char islem;
and read it using scanf
passing a pointer:
scanf(" %c", &islem);
Then compare using normal comparison operator instead:
if (islem == '+') {
toplama(sayiBir, sayiIki, sonuc);
}
On another note, you don't need the sonuc
variable, and should not pass it to the functions. Instead the function can define the result
variable locally:
void carpim(int numOne, int numTwo){
int result = numOne * numTwo;
printf("Sonuc: %d", result);
}
And you don't really need the result
variable either:
void carpim(int numOne, int numTwo){
printf("Sonuc: %d", numOne * numTwo);
}