I'm writing a program for a simple calculator that accepts a string (without spaces) with two operators and one operand and outputs the result. My program compiles just fine but during runtime, I'm getting the windows stopped working error message. What could be the reason for it? I think it's good something to do with my program's logic. Here's my code:
#include <stdio.h>
#include <math.h>
int main()
{
int operand_1 = 0, operand_2 = 0, i = 0, result = 0;
char string[10], *ptr, operation;
ptr = string;
printf("Enter the expression:\n");
gets(string);
//puts(string);
while(*ptr==0||*ptr==1||*ptr==2||*ptr==3||*ptr==4||*ptr==5||*ptr==6||*ptr==7||*ptr==8||*ptr==9)
{
operand_1 = operand_1 + ((int)*ptr)*pow(10,i);
i++;
ptr++;
}
operation = *ptr;
ptr++;
i=0;
while(ptr!=NULL)
{
operand_2 = operand_2 + ((int)*ptr)*pow(10,i);
i++;
ptr++;
}
switch(operation)
{
case '+':
result = operand_1 + operand_2;
case '-':
result = operand_1 + operand_2;
case '*':
result = operand_1 * operand_2;
case '/':
result = operand_1 / operand_2;
case '%':
result = operand_1 % operand_2;
}
printf("%d",result);
}
I've resolved the problem and also improved the logic of the program so that it works fine.
#include <stdio.h>
#include <math.h>
int main()
{
while(1)
{
int operand_1 = 0, operand_2 = 0, i = 0, result = 0;
char string[10], *ptr, operation;
ptr = string;
printf("\nEnter the expression:");
scanf("%s",string);
if (*ptr=='q' || *ptr=='Q' && *(ptr+1)=='u' || *(ptr+1)=='U' && *(ptr+2)=='i' || *(ptr+2)=='I' && *(ptr+3)=='t' || *(ptr+3)=='T')
{
printf("\nBye");
break;
}
while(*ptr>='0' && *ptr<='9')
{
operand_1 = operand_1*10 + (*ptr - 48);
i++;
ptr++;
}
operation = *ptr;
ptr++;
i=0;
while(*ptr>='0' && *ptr<='9')
{
operand_2 = operand_2*10 + (*ptr-48);
i++;
ptr++;
}
if(operand_2 == 0)
{
printf("\nDivision by zero");
continue;
}
switch(operation)
{
case '+':
result = operand_1 + operand_2;
break;
case '-':
result = operand_1 - operand_2;
break;
case '*':
result = operand_1 * operand_2;
break;
case '/':
result = operand_1 / operand_2;
break;
case '%':
result = operand_1 % operand_2;
break;
}
printf("\nResult = %d",result);
}
}
Hope it helps someone in need :)
Related
I have a function for translating the fractional part of the entered number into another number system (not the most beautiful code):
void FracToAny(double D, int q, int t)
{
double b[10] = {0};
for (int i = 1; i < t; i++)
{
double DP = D * q;
D = modf(DP, &b[i]);
if (D == 0)
{
break;
}
D = DP - b[i];
}
for (int i = 0; i < t; i++)
{
if (q == 16)
{
switch ((int)b[i])
{
case 10:
printf("A");
break;
case 11:
printf("B");
break;
case 12:
printf("C");
break;
case 13:
printf("D");
break;
case 14:
printf("E");
break;
case 15:
printf("F");
break;
default:
printf("%d", (int)b[i]);
break;
}
}
}
}
As a result, I get an array of double, which is a character-by-character representation of the resulting fractional part. However, I would like to return this value from the function in the form of "0.result". How can I do this?
It would be good not to use union or dynamic memory allocation (I've seen them trying to find a solution to the problem). I'd like to make it as simple as possible.
I think this is what you are trying to do (see my comment above):
Mac_3.2.57$cat etFract.c
#include <stdio.h>
#include <math.h>
int main(void)
{
int i;
double D;
int t = 3;
double b[10] = {0};
D = (3 * 16*16*16 + 4 * 16*16 + 5 *16)/(16*16*16.0);
printf("translating %f...\n", D);
for(i = 0; i < t; i++){
b[i] = modf(D, &D);
if(D == 0){
break;
}
D = b[i] * 16;
}
printf("0.");
for(int i = 0; i < t; i++){
switch((int)b[i]*16){
case 10:
printf("A\n");
break;
case 11:
printf("B\n");
break;
case 12:
printf("C\n");
break;
case 13:
printf("D\n");
break;
case 14:
printf("E\n");
break;
case 15:
printf("F\n");
break;
default:
printf("%d", (int)(b[i]*16));
break;
}
}
printf("\n");
return(0);
}
Mac_3.2.57$cc etFract.c
Mac_3.2.57$./a.out
translating 3.269531...
0.450
Mac_3.2.57$
I wrote a program which is used to evaluate postfix expression, I am not getting any compiler error/warnings but I am not getting the correct output, which probably means the issue is with the calculation but I don't know where.
My Code:
#include <ctype.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX 20
char s[MAX], top = 0;
void main() {
char postfix[MAX], ch;
int i, op1, op2, res;
clrscr();
printf("\n\t\t program to evaluate postfix expression");
printf("\n\t\t.......");
printf("\n enter the postfix expression:\n");
scanf("%s", &postfix);
for (i = 0; i < strlen(postfix); i++) {
ch = postfix[i];
if (isdigit(ch))
push(ch = '0');
else {
op2 = pop();
op1 = pop();
switch (ch) {
case '+':
res = op1 + op2;
break;
case '-':
res = op1 - op2;
break;
case '*':
res = op1 * op2;
break;
case '/':
res = op1 / op2;
break;
case '^':
res = pow(op1, op2);
break;
default:
printf("invalid choice");
}
push(res);
}
}
printf("result of above expression is:%d\n", pop());
getch();
}
push(int element) {
++top;
s[top] = element;
}
int pop() {
int element;
element = s[top];
--top;
return (element);
}
You should fix the typo and change push(ch = '0'); to
push(ch - '0');
ch is a character, isdigit(ch), or better isdigit((unsigned char)ch) tells you it is a digit, ch - '0'is the digit value, a number in the range0to9`.
Your code ch = '0' stores the digit '0' into ch and pushes this value, which is the character code or 0 on your system, 48 in ASCII.
This program is about converting Roman number to decimal number. The program can convert the alphabet to number but it can not process the last roman digit. I think my flow is alright but the output is not right. Can any body give me a helping hand?
#include <stdint.h>
#include <stdio.h>
#include <string.h>
int roman_to_int(const char s[], int length) {
// Please complete the function body
int ans = 0, value[length];
for (int i = 0; i < length; i++) {
switch (s[i]) {
case 'I': value[i] = 1; break;
case 'V': value[i] = 5; break;
case 'X': value[i] = 10; break;
case 'L': value[i] = 50; break;
case 'C': value[i] = 100; break;
case 'D': value[i] = 500; break;
case 'M': value[i] = 1000; break;
}
}
for (int i = 0; i < length - 1; i++) {
if (value[i] >= value[i+1])
ans += value[i];
else {
ans = ans + value[i+1] - value[i];
i++;
}
}
return ans;
}
int main() {
char roman_num[] = "III";
char roman_num_2[] = "CXXIII";
char roman_num_3[] = "MMMCDLIX";
printf("roman_to_int(%s) = %d\n", roman_num,
roman_to_int(roman_num, strlen(roman_num)));
printf("roman_to_int(%s) = %d\n", roman_num_2,
roman_to_int(roman_num_2, strlen(roman_num_2)));
printf("roman_to_int(%s) = %d\n", roman_num_3,
roman_to_int(roman_num_3, strlen(roman_num_3)));
}
You should add the value of the last roman digit after the end of the second loop.
As an alternative, you could make value on entry longer than n and set the last entry to 0 so you won't need the make a special case of the last roman digit.
Note that you should also handle the case of unrecognised roman digits: either by ignoring them or by returning an error code, such as a negative value -1.
It is also simpler for roman_to_int to take a null terminated C string and compute the length there.
Here is a modified version:
#include <stdio.h>
#include <string.h>
int roman_to_int(const char s[]) {
// Please complete the function body
int length = strlen(s);
int ans = 0, value[length + 1];
for (int i = 0; i < length; i++) {
switch (s[i]) {
case 'I': value[i] = 1; break;
case 'V': value[i] = 5; break;
case 'X': value[i] = 10; break;
case 'L': value[i] = 50; break;
case 'C': value[i] = 100; break;
case 'D': value[i] = 500; break;
case 'M': value[i] = 1000; break;
default: return -1;
}
}
value[length] = 0;
for (int i = 0; i < length; i++) {
if (value[i] >= value[i + 1])
ans += value[i];
else
ans -= value[i];
}
return ans;
}
int main() {
char roman_num[] = "III";
char roman_num_2[] = "CXXIII";
char roman_num_3[] = "MMMCDLIX";
char roman_num_4[] = "MMMCDLIZ"; // error
printf("roman_to_int(%s) = %d\n", roman_num, roman_to_int(roman_num));
printf("roman_to_int(%s) = %d\n", roman_num_2, roman_to_int(roman_num_2));
printf("roman_to_int(%s) = %d\n", roman_num_3, roman_to_int(roman_num_3));
printf("roman_to_int(%s) = %d\n", roman_num_4, roman_to_int(roman_num_4));
return 0;
}
I am trying to carry out left to right evaluation in C. No order of precedence whatsoever. So 5+3*2 should be 16. I know how to do that with 2 numbers and an operator, however, I cannot figure out how to do the same thing for an expression like 2+4-5+2.
This is what I have for 2 numbers:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 20
int main(void)
{
char exp[SIZE];
int ans,c, i=0;
int length;
printf("Enter your expression: ");
fgets(exp, 20, stdin);
length = strlen(exp);
--length;
for(int j=0; j<length; j++)
{
while (exp[i]!='\n')
{
// putchar(exp[i]);
i++;
switch (exp[i])
{
case '+':
ans = (exp[i]-'0') + (exp[2]-'0');
printf("The answer is %d\n", ans);
break;
case '-':
ans = (exp[0]-'0') - (exp[2]-'0');
printf("The answer is %d\n", ans);
break;
case '*':
ans = (exp[0]-'0') * (exp[2]-'0');
printf("The answer is %d\n", ans);
break;
case '/':
ans = (exp[0]-'0') / (exp[2]-'0');
printf("The answer is %d\n", ans);
break;
default:
break;
}
}
}
exit(0);
}
Any help is appreciated.
Assuming alternating numbers and operators with single-character numbers (which seems to be what you assumed), a minimal implementation similar to your original implementation is:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 20
int main(void) {
char exp[SIZE];
int ans, length, i;
printf("Enter your expression: ");
fgets(exp, 20, stdin);
ans = exp[0] - '0';
length = strlen(exp) - 1;
for (i = 0; i < length && exp[i] != '\n'; i++) {
switch (exp[i]) {
case '+':
ans += exp[i+1] - '0';
break;
case '-':
ans -= exp[i+1] - '0';
break;
case '*':
ans *= exp[i+1] - '0';
break;
case '/':
ans /= exp[i+1] - '0';
break;
default:
break;
}
}
printf("The answer is %d\n", ans);
return 0;
}
As per your given example, assumed that each number will be single digit number.
Try this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 20
int main(void)
{
char exp[SIZE];
int ans,c, i=0;
int length,j;
printf("Enter your expression: ");
fgets(exp, 20, stdin);
length = strlen(exp);
char ch;
ans = exp[i]-'0';
i++;
while (i <= length)
{
switch (exp[i])
{
case '+':
i++;
ans += (exp[i]-'0');
break;
case '-':
i++;
ans -=(exp[i]-'0');
break;
case '*':
i++;
ans *=(exp[i]-'0');
break;
case '/':
i++;
ans /= (exp[i]-'0');
break;
default:
break;
}
i++;
//printf("The answer is %d\n", ans);
}
printf("The answer is %d\n", ans);
exit(0);
}
I am writing a calculator program in c using stack, In below program I used concept of infix to postfix conversion and next postfix evaluation.
I am getting correct answer for 1+2 answer is 3 but for 11+1 or any two and more digit i am getting wrong answer.
Can anyone help me what I will include in my code so that it work for more than two digit like 28+25 or any?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define SIZE 50 /* Size of Stack */
int top = -1;
char pofx[50];
char s[SIZE];
int infix_to_postfix() {
char infx[50], ch;
int i = 0, k = 0;
void push(char elem) { /* Function for PUSH operation */
s[++top] = elem;
}
char pop() { /* Function for POP operation */
return (s[top--]);
}
int pr(char elem) { /* Function for precedence */
switch (elem) {
case '#':
return 0;
case '(':
return 1;
case '+':
case '-':
return 2;
case '*':
case '/':
return 3;
}
return -1;
}
printf("\n\nEnter a Value to calculate : ");
gets(infx);
push('#');
while ((ch = infx[i++]) != '\0') {
if (ch == '(') push(ch);
else if (isalnum(ch)) pofx[k++] = ch;
else if (ch == ')') {
while (s[top] != '(')
pofx[k++] = pop();
char elem = pop(); /* Remove ( */
} else { /* Operator */
while (pr(s[top]) >= pr(ch))
pofx[k++] = pop();
push(ch);
}
}
while (s[top] != '#') /* Pop from stack till empty */
pofx[k++] = pop();
pofx[k] = '\0'; /* Make pofx as valid string */
printf("\n\nGiven Infix Expn: %s Postfix Expn: %s\n", infx, pofx);
return (int) pofx[k];
}
void postfix_evaluate() {
char ch;
int i = 0, op1, op2;
void pushit(int elem) { /* Function for PUSH operation */
s[++top] = elem;
}
int popit() { /* Function for POP operation */
return (s[top--]);
}
infix_to_postfix();
while ((ch = pofx[i++]) != '\0') {
if (isdigit(ch)) pushit(ch - '0'); /* Push the operand */
else { /* Operator,pop two operands */
op2 = popit();
op1 = popit();
switch (ch) {
case '+':
pushit(op1 + op2);
break;
case '-':
pushit(op1 - op2);
break;
case '*':
pushit(op1 * op2);
break;
case '/':
pushit(op1 / op2);
break;
}
}
}
printf("\n Given Postfix Expn: %s\n", pofx);
printf("\n Result after Evaluation: %d\n", s[top]);
}
int main() {
postfix_evaluate();
return 0;
}
part of my own code that might be useful:
if (isdigit(gi.n.nch))
{
gi.x = chr2num(gi.n.nch);
gi.n= nextchar( gi.n, len, instr);
while(isdigit(gi.n.nch))
{
gi.x *= 10;
gi.x += chr2num(gi.n.nch);
gi.n= nextchar( gi.n, len, instr);
}
}