开发者

c assignment, averaging integers

I worked on this yesterday about 5 hours and got the code to work using help from this site, but I think the way I did it was a cheater way, I used a scanf command. Anyways I want to fix this the correct way. Thanks guys! Oh the code compiles but the average that gets spit out is wrong. I would like to conceptually understand what I am doing wrong as well as finish the assignment.

#include <stdio.h> 
#include <stdlib.h>
double get_number(int num);


main () {
  double n1,n2,n3;
  double average;

  printf("\nCompute the average of 3 integers\n");
  printf("--------------------------------\n");
  n1 = get_number(1);
  n2 = get_number(2);
  n3 = get_number(3);
  average = (n1 + n2 + n3)/3;
  printf("The average is %0.2f\n",average);
}

double get_number(int num) { 
  double value = 0;
  int c;
  printf("Please input number %i: ", num);
  while ((c = getchar()) != '\n') { 
    if ( (c<'0') || (c>'9') ) { 
      printf("Incorrect charact开发者_JS百科er entered as a number - %i\n",c);
      exit(-1);
    }
    else {
      c =value;
    }
  }
  return(value);
}


Your get_number function always returns 0, because you never assign anything to the value variable. I'm guessing you want:

value = value*10 + (c - '0');

Instead of

c = value;

To clarify:

You are reading a number digit by digit (with getchar you read a single character). So let's say you read the digits 1 2 3:

When you read 1, you do value = value*10 + ('1' - '0') meaning value = 0 + 1 = 1.

When you read 2, you do the same and get value = 1*10 + ('2' - '0') meaning value = 12.

Same for 3.

What you need to understand is that multiplying something by 10 adds a 0 at the end of that something. Adding a digit to something that ends with a zero replaces that 0 by that digit.

You must also understand that you are dealing with characters, which are actually integers. The character '0' is represented by an ASCII code of let's say x. '1' is represented by x + 1 etc. If you were to print the value of '0'+'3' it would not be 3 as you'd expect. This is why we subtract '0' (which is x) from the characters, to get the actual digits.

Hope that clears some things up.


  1. Given the character corresponding to a digit, you need to get the digit itself. For example, you want to get the number 0, not the number 48 (the ASCII code for the character '0'). There's a trick for this if your characters are ASCII, which involves the fact that the digits start sequentially at '0', and the fact that you can 'subtract' characters from each other.

  2. You need to build up the number using digits you've already entered. It would help if you had an operation that can move a digit to the 10s column, from the 10s column to the 100s column, and so on. Can you think of what that operation is?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜