I'm supposed to write a program that accepts two interger vallues typed by the user. Then display the results of dividing the first interger by the second, to three decimal place accuracy. It is supposed to be able to check for division by 0 and must use a conditional operator.
My idea was to float variables a b c
have the user input a and b then make a conditional operator stating
c = (b==0) ? .454 : a/b;
if(c==.454)
printf("Dividing by 0 is undefined");
else
printf("The answer is %f\n" c)
It's ghetto and its obviously bad programming, I know.
I get a floating exception when I make a and b and type of integer which I don't understand.
I'm going to drop this class this week because I need to face that I have absolutely no aptitude for this programming language, but I would still like learn just in case I attempt it again next semester.
Can anyone guide me?
Can I have someone look at this C programming problem?
hi,
please try the following code:
c = (b==0) ? 0 : a/b;
if(b==0)
printf("Dividing by 0 is undefined");
else
printf("The answer is %f\n" c)
The problem is that you should not use floating point variables for comparison.
Reply:the conditional operator has the same effect as the logical IF.
i dont see use of ur first line, i miss the logical programming in it.. what if b is = to 0 and c not, what if the opposite??
i suggest that simply check for a,b, and c different than 0 and then do ur division operation..
about droping ur class, i dont think it is a rigt decision, programming courses need a lot of patience... but believe me, once u got the keys u ll master it
if u think u ll only need class attendance for ur class then u r wrong.. it needs more, and it needs lot of practises and exercises, u ll have to do programming as a hobby, and love it more than a hobby..
it is not easy, but believe me it is worthy
good luck :)
Reply:The code above looks fine. Can you post your entire code? It's not bad programming above.
Just to clarify as well: is it printf("The answer is %f\n" c) or printf("The answer is %f\n" , c) (with the comma) in your code?
EDIT: Yeah there is the issue of floating point comparisons as well. The above code works.
Reply:do something like this:
int main ...
get int a from user
get int b from user
if b == 0 then
print "error: cannot divide by zero"
else {
float afloat = (float)a;
float bfloat = (float)b;
print "answer is: %0.3f", afloat / bfloat
}
return 0;
--
Change the above to correct C syntax.
Since you cannot divide two integers to get a float then you must change the int to float.
ovary
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment