# Basic C calculator

Page 1 of 1

## 3 Replies - 1924 Views - Last Post: 18 November 2012 - 11:40 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=300704&amp;s=a82acc3a634ebe92a7fe6e694604166a&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 dok300

Reputation: 0
• Posts: 16
• Joined: 27-October 12

# Basic C calculator

Posted 18 November 2012 - 01:43 PM

Hi

I'm trying to create a simple calculator in C.

So far this is what I've got.

```
#include<stdio.h>
#include<stdlib.h>

int main(void)

{

char ch;
int a,b;

printf ("Would you like to add,multiply,
subtract or divide? Press,a,m,s or d for your choice");
ch = getchar();

if ('%c'= a)
{
scanf("%d%d",a,B)/>;
}

if('%c'= m)
{
printf("enter two numbers to multiply");
scanf("%d%d",a,B)/>;
mult_total = a*b;
}

if
('%c'= s){
printf("enter two numbers to subtract");
scanf("%d%d",a,B)/>;
sub_total = a-b;
}

if ('%c'= d) {
printf("enter two numbers to divide");
scanf("%d%d",a,B)/>;
div_total = a/b;

}
else{
printf("Not a valid selection");
}
return (0);

}
```

I am fully aware that there is probably a much easier one line way of doing all this but i want to learn what is wrong with this code.( Of course this is not to say any alternative solutions are not welcomed!)

Any input appreciated.

Is This A Good Question/Topic? 0

## Replies To: Basic C calculator

### #2 Xupicor

• Nasal Demon

Reputation: 337
• Posts: 870
• Joined: 31-May 11

## Re: Basic C calculator

Posted 18 November 2012 - 02:07 PM

Lines akin to this one:
```if('%c'= m)
```
What does that even mean? It shouldn't compile, and if it didn't, then you should post complete compile log.

• Saucy!

Reputation: 6208
• Posts: 23,953
• Joined: 23-August 08

## Re: Basic C calculator

Posted 18 November 2012 - 03:46 PM

And another that needs to read the manual for scanf.

### #4 raghav.naganathan

• Perfectly Squared ;)

Reputation: 410
• Posts: 1,440
• Joined: 14-September 12

## Re: Basic C calculator

Posted 18 November 2012 - 11:40 PM

Ideally,for a basic calculator, you might want to use a switch statement.So basically what you may need are 2 variables for the numbers,and of course, the operator.

Ask the user to enter 2 numbers.
Ask the user to provide an operator for these 2 numbers and save it in a char variable say op.
```switch(op)
{
case '+' : //code for addition and of course, break;
case '-' : //code for subtraction and of course, break;
}
```

similarly for the other operators like *,/ and %(modulo)

P.S : As my esteemed DIC members have suggested, you need to look into the syntax of scanf()

regards,
Raghav

This post has been edited by raghav.naganathan: 18 November 2012 - 11:43 PM