chciałbym napisać program który sumuje wszystkie nieparzyste cyfry z wprowadzonej liczby i wyświetla wynik (np. wprowadzamy 693. 9+3=12 ) tylko nie wiem jak się za to zabrać.
0
1
Zamieniasz liczbę na stringa, iterujesz po znakach (cyfrach), sprawdzasz czy parzyste, jeśli nie -> dodajesz do sumy.
2
#include <iostream>
#include <numeric>
using namespace std;
int main() {
string s;
while (cin >> s) {
cout << "Suma dla: " << s << " = " << accumulate(begin(s), end(s), 0,
[](int a, int x) { return a + (x % 2 ? x & 0xf : 0); });
}
return 0;
}
0
vpiotr napisał(a):
#include <iostream> #include <numeric> using namespace std; int main() { string s; while (cin >> s) { cout << "Suma dla: " << s << " = " << accumulate(begin(s), end(s), 0, [](int a, int x) { return a + (x % 2 ? x & 0xf : 0); }); } return 0; }
https://ideone.com/qGnpcQ
A bez biblioteki numeric się nie da ?
0
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include <string.h>
#define MAXSIZE 256
int main(void)
{
uint8_t buff[MAXSIZE];
memset(buff, '\0', sizeof(buff)/sizeof(buff[0]));
scanf("%s", buff);
uint32_t sum = 0;
for (int i = 0; i < MAXSIZE; ++i)
{
uint8_t sign[2];
sign[0] = buff[i];
sign[1] = '\0';
if ('\0' == sign[0]) break;
else
{
int var = atoi(sign);
if (var & 0x01) sum += var;
}
}
printf("Suma: %u\n", sum);
return 0;
}
Prościej się chyba nie da. Pozdro
https://ideone.com/47Ie0t
0
#include <iostream>
#include <string>
int main()
{
int sum{};
std::string num;
std::cin >> num;
for (auto const& el : num)
{
int tmp = el - '0';
if (tmp % 2 == 1)
sum += tmp;
}
std::cout << sum << std::endl;
}
Tak też będzie prosto.