home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.sys.amiga.programmer
- Path: EU.net!sun4nl!hguijt
- From: hguijt@inter.NL.net (Hans Guijt)
- Subject: Re: silly c problem
- Message-ID: <DM8sCu.Huy@inter.NL.net>
- Organization: NLnet
- X-Newsreader: TIN [version 1.2 PL2]
- Date: Sun, 4 Feb 1996 08:17:18 GMT
-
- silly c problem
-
- Others already pointed out the problem with this code, but as a matter of
- style, why not use a switch? You wrote:
-
- >#include <stdio.h>
- >
- >main()
- >{
- > int num1, num2, res, ope, err;
- >
- > printf("Please input two number!n");
- > scanf("%d%d", &num1, &num2);
- > printf("You entered %d and %d.nn", &num1, &num2);
- > printf("And now the code for the operation!n");
- > printf("1=Add, 2=Subtract, 3=Multiply, 4=Dividen");
- > scanf("%d", &ope);
- > printf("You entered %d.nn", &ope);
- > err = 1;
- > if(ope == 1)
- > {
- > res = num1 + num2;
- > err = 0;
- > }
- > if(ope == 2)
- > {
- > res = num1 - num2;
- > err = 0;
- > }
- > if(ope == 3)
- > {
- > res = num1 * num2;
- > err = 0;
- > }
- > if(ope == 4)
- > {
- > res = num1 / num2;
- > err = 0;
- > }
- > if(err == 1)
- > printf("Wrong Code! Input only number 1 - 4!n");
- > else
- > printf("The result is %d %d %d %dn.", &num1, &num2, &res, &err);
- >}
-
- whereas you could have written:
-
- #include <stdio.h>
-
- main()
- { int num1, num2, res, ope, err;
-
- printf("Please input two number!\n"); // you probably meant \n?
- scanf("%d%d", &num1, &num2);
- printf("You entered %d and %d.\n\n", &num1, &num2);
- printf("And now the code for the operation!\n");
- printf("1=Add, 2=Subtract, 3=Multiply, 4=Dividen");
- scanf("%d", &ope);
- printf("You entered %d.\n\n", &ope);
- err = 0; // note how err is initialized to 0 rather than 1
- switch (ope) {
- case 1:
- res = num1 + num2;
- break;
- case 2:
- res = num1 - num2;
- break;
- case 3:
- res = num1 * num2;
- break;
- case 4:
- res = num1 / num2; // be careful not to decide by 0
- break;
- default:
- err = 1;
- }
-
- if(err == 1)
- printf("Wrong Code! Input only number 1 - 4!\n");
- else
- printf("The result is %d %d %d %dn.", &num1, &num2, &res, &err);
- }
-
-
- Bye,
-
- Hans
-
-