Calculator returns same number

October 6, 2010 at 22:10:03
Specs: Windows 7
I'm a total newb to C/C++ and I can't figure out why my program continues to spit out the same number. Whenever I enter numbers I always get 4206 and so on. Any help would be appreciated. Here's my code:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

char szOp;
int nAN;
int nAM;
int nFW;
int nAnsr;

int ask(){

printf("Press + for Percentage Calculator (+,-,/,x)\n");
scanf("%s", &szOp);
printf("Please enter Atomic Number\n");
scanf("%d", &nAN);
printf("Please enter Atomic Mass\n");
scanf("%d", &nAM);
printf("Please enter Formula Weight\n");
scanf("%d", &nFW);

return 0;

int calculate(){
case '+':
nAnsr = ((((float)nAN * (float)nAM) * 100) / (float)nFW);

int show(){
printf("The result is %d\n", "nAnsr");

int main(){


return 0;

See More: Calculator returns same number

Report •

October 7, 2010 at 00:58:24
why not declare your vars as floats instead of casting ints? Your result will be truncated anyway.

if szOp is of type char, then scanf should be "%c", &szOp and not "%s", &szOp

if printf("The result is %d\n", "nAnsr"); isn't a typo, I'd suspect the problem is with "nAnsr" having the quotes. :D


I have no aspiration for preaching. ;-)

Report •

October 7, 2010 at 06:25:54
Thank you so much! Getting rid of the quotes fixed the problem. Also I've been trying to convert the ints to floats or double, but I just can't seem to get it to work. Where would I implement it into the code?

Report •

October 7, 2010 at 15:10:00
No worries. :)

In C, the format specifier for the float is "%f" and the double, I tend to use "%lf". That's a lowercase "L" and not an i or 1. You'd use that with either your scanf or printf.

float var = 0.2f;  // compiler tends to warn about double without the 'f'
printf("%0.2f", var); // output 0.20

if(scanf("%f", &var) != 1) {
   // bad input for data type 
} else {
   // do something with value in var

One other pitfall; with the char array and scanf, you wouldn't use the "address of" operator... '&'

char buffer[80];
scanf("%79s", buffer); // save room for the '\0' character

In general, scanf is bad function to use for input... especially numerical input. You can greatly reduce the chance of stream errors by always using a character array for input. If you require numberical input, you can either use sscanf or the strto family of conversion functions.

char buffer[80];
int number;

do {
   printf("Enter a number: ");
   fgets(buffer, sizeof buffer, stdin);
} while((sscanf(buffer, "%d", &number)) != 1);

printf("You entered %d", number);

Hope that helps.

I have no aspiration for preaching. ;-)

Report •

Related Solutions

Ask Question