U E D R , A S I H C RSS

새싹교실/2011/Pixar/실습 (rev. 1.1)

새싹교실/2011/Pixar/실습

HW 1

각 자리 수 더하기

Write a program that reads a four digit integer and prints the sum of its digits as an output.
  • Simple Implementation

#include <stdio.h>
#include <math.h>
int main(){
	int four_digit_num, sum = 0, i, positional;

	scanf("%d", &four_digit_num);

	for(i = 3; i >= 0; i--){
		positional = pow(10, i);
		sum += four_digit_num / positional;
		four_digit_num %= positional;
	}
	printf("%d\n", sum);
	return 0;

}
  • Basic Implementation

#include <stdio.h>

int main(){
	int four_digit_num, sum = 0, i, positional, j;

	scanf("%d", &four_digit_num);

	for(i = 3; i >= 0; i--){
		positional = 1;
		for(j = 0; j < i; j++){
			positional *= 10;
		}	
		sum += four_digit_num / positional;
		four_digit_num %= positional;
	}
	printf("%d\n", sum);
	return 0;
}
  • Advanced Implementation

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

int main(){
	int n_digit_num, sum = 0, positional, n;

	scanf("%d", &n_digit_num);
	
	n = log10(n_digit_num);

	if((n_digit_num >= pow(10, n)) && (n_digit_num < pow(10, n+1))){

		for(; n >= 0; n--){
			positional = pow(10, n);
			sum += n_digit_num / positional;
			n_digit_num %= positional;
		}
		printf("%d\n", sum);
		return 0;
	}

	exit(1);
}

Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2021-02-07 05:29:42
Processing time 0.0222 sec