View Single Post
Old 14-11-2007, 07:57 PM   #389 (permalink)
[xubz]
"The Cake is a Lie!!"
 
[xubz]'s Avatar
 
Join Date: Oct 2006
Posts: 471
Default Re: Post ur C/C++ Programs Here

A Command Line Calculator.

I coded this because sometimes if I quickly wanted to multiply/divide some numbers, I'd hate to open up the Calculator App (especially in Linux).

Just cal 2 + 2 or cal 100 / 39 would throw up the result. Much Better

Code:
#include<stdio.h>
#include<stdlib.h>

int main(int argc, char *argv[])
{
	float a, b;
	char op;

	if (argc < 4 || argc > 4)
	{
		printf("\nUsage: cal <number1> <operator> <number2>\n");
		printf("\nValid Expressions: + - * /\n");
		printf("\nExample: cal 2 + 2\n");
		exit(1);
	}

	/* Store the Command Line Arguments in Local Variables */
	a = atof(argv[1]);
	b = atof(argv[3]);
	op = *argv[2];

	switch(op)
	{
		case '+':
			printf("\n%f", (float)a+b);
			break;

		case '-':
			printf("\n%f", (float)a-b);
			break;

		case '*':
			printf("\n%f", (float)a*b);
			break;

		case '/':
			printf("\n%f", (float)a/b);
			break;

		default:
			printf("\nInvalid Operator");
			break;
	}

	printf("\n");
	return(0);
}
Tested to compile and work using GCC under Linux
__________________
[xubz] ● http://xubz.com/
[steam_id] ● http://steamcommunity.com/id/xubz
[xubz] is offline