types - calculator error in C -
i'm trying make calculator program in c. i've done of think...just output incorrect. output supposed come out doesn't. below code calculator program!.
#include <stdio.h> #include <string.h> #include <stdlib.h> void add(double num1,double num2); void del(double num1,double num2); void mul(double num1,double num2); void divide(double num1,double num2); main(){ file *fp; char sym; float num1, num2; int ret; fp = fopen("input.txt","r"); if(fp==null){ exit(1); } while(fscanf(fp,"%f%c%f", &num1,&sym,&num2)!=eof){ switch(sym){ case '+': add(num1,num2); break; case '-': del(num1,num2); break; case '*': mul(num1,num2); break; case '/': divide(num1,num2); break; default: printf("%f%c%f", num1,sym,num2); } } fclose(fp); } void add(double num1,double num2){ double result; result = num1+num2; printf("%f\n", result); } void del(double num1,double num2){ double result; result = num1-num2; printf("%f\n", result); } void mul(double num1,double num2){ double result; result = num1*num2; printf("%f\n", result); } void divide(double num1,double num2){ double result; result = num1/num2; printf("%f\n", result); }
when have inputs of:
123456789+987654321 123456789-987654321 12345*54321 1349.238912+12384.12871 3918.381631-1287.38272
the results i'm supposed following:
1111111110.000000 -864197532.000000 670592745.000000 13733.367622 2090.998911
but these results get:
1111111128.000000 -864197544.000000 670592745.000000 13733.367798 2090.998901
and i'm not sure why middle operation works when rest doesn't i've tried using float data type num1
, num2
, results far more off using double.
in response question in comments said regarding streamlining program, consider following code:
note included revisions code reflecting original problem. namely, using float
data type being implicitly cast double
followed printf() call float
specifiers.
#include <stdio.h> #include <stdlib.h> main(){ file *fp; char sym; double num1, num2; fp = fopen("input.txt","r"); if(fp == null) exit(1); while( fscanf(fp,"%f%c%f", &num1,&sym,&num2) != eof ) switch(sym){ case '+': printf("%f\n", num1+num2); break; case '-': printf("%f\n", num1-num2); break; case '*': printf("%f\n", num1*num2); break; case '/': printf("%f\n", num1/num2); break; default: printf("%f%c%f", num1,sym,num2); } fclose(fp); }
notice reduced brackets well. required include brackets statements have multiple statements depend on it.
as in:
if(myvar == 1){ printsomething(); dosomething(); dosomethingelse(); }
however, if require 1 statement can drop brackets.
if(myvar == 1) printsomething();
note if have single block
of code follows still can drop brackets (as same code above - while loop has single switch-case).
Comments
Post a Comment