c++ - Obtaining quotient with remainder using just arithmetic operators -
i'm starting learn basics of c++ i'm stumbled upon issue.
for example, i'm trying convert celcius fahrenheit.
assuming, have fixed formula.
f = 9/5(c) + 32 i'm aware mathematically possible break down
mathematically : (9c/5) + 32 however, i'll not able obtain quotient reminder
so how obtain both quotient reminder using arithmetic operators or impossible
i tested out still refuses give me correct output
#include<iostream> using namespace std; int main(){ double f; int c; cout<<"enter degree celcius:"<<endl; cin>>c; cout<<endl; f = 9/5 * c + 32; //incorrect ways obvious reason f = 9%5 * c + 32; //incorrect ways obvious reason cout<<c<<"degree celcius equals to:"<<f<<endl; }
f = 9/5 * c + 32; //incorrect ways obvious reason
if knew "obvious reason" why incorrect, wouldn't asking question!
it incorrect because calculation integer values. 9, 5, c, , 32 ints, , when mathematical operations ints, c++ gives result int. because integers whole numbers, not have decimal portion , cannot store remainder.
after calculation done, assign result f, double. although floating-point types have decimal portion can store remainder, you've done here convert integer result floating-point value.
you can think of code being equivalent to:
int result = 9/5 * c + 32; f = static_cast<double>(result); in order fix problem, need force calculation done floating-point:
f = 9.0/5.0 * static_cast<double>(c) + 32.0; this preserve "remainder" decimal portion of floating-point value, f.
technically, need single intermediate operation yield floating-point result. if first operation results in floating-point value, remaining operands promoted floating-point match initial operand. do:
f = 9.0/5 * c + 32; (9.0 double literal, 9 integer literal. adding decimal portion (.x) turns double. if had written 9.0f, float literal.)
Comments
Post a Comment