How to sum the digits of float in C

2 Answers

0 votes
#include <stdio.h>
 
int sumDigits(long num) {
    int sum = 0;
    while (num != 0) {
        sum += num % 10;
        num /= 10;
    }
     
    return sum;
}

int main(void)
{
    float pi = 3.141592;

	long long ll = pi * 1000000; 

	printf("%llu \n",ll); 
	
	int sum = sumDigits(ll);
    
    printf("%d\n", sum);   
     
    return 0;
}
  
   
   
   
/*
run:

3141592 
25

*/

 



answered Nov 10, 2023 by avibootz
edited Jul 21, 2024 by avibootz
0 votes
#include <stdio.h>
  
void remove_char_from_string(char str[], char ch) { 
    int j; 
       
    for (int i = j = 0; str[i] != '\0'; i++) {
         if (str[i] != ch) {
             str[j++] = str[i]; 
         }
    }
       
    str[j] = '\0'; 
} 

int sum_the_digits_of_float(float f) {
    char str[32] = "";
    int sum = 0;
 
    sprintf(str, "%f", f);
    remove_char_from_string(str, '.');
    puts(str);

    int i = 0;
    while (str[i]) {
        sum += str[i] - '0';
        i++;
    } 
    
    return sum;
}
 
int main(void)
{
    float f = 3.141592;
   
    int sum = sum_the_digits_of_float(f);
    
    printf("%d\n", sum);   
      
    return 0;
}

    
    
/*
run:
 
3141592 
25
 
*/

 



answered Jul 21, 2024 by avibootz
edited Jul 21, 2024 by avibootz
...