[英]how to get large numbers as input?
嗨,我真的是c ++的新手,我想編寫一個從用戶那里接收數字並對其數字求和的代碼,並一直這樣做,直到獲得一位數字並返回結果為止。 但是我注意到,當我的數字很大(例如15位數字長)時,錯誤的數字存儲在我聲明用於存儲用戶輸入的變量中。 我該怎么辦?
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int get_sum(long x) {
cout << x<<endl;
if (x < 10) {
return x;
}
else {
string num_in_str = to_string(x);
long result=0;
for (int i = 0; i < num_in_str.size(); i++) {
int digit = num_in_str[i] - '0';
result += digit;
}
return get_sum(result);
}
}
int main()
{
long input;
cin >> input;
int final_result = get_sum(input);``
cout << final_result;
}
哦,我知道了。 我不得不使用uint64_t數據類型
C ++中的整數數據類型最多可以存儲數字。 特別是,根據平台和編譯器的不同,“ long”可以是32位或64位,最多可以存儲2 ^ 31-1或2 ^ 63-1。 如果要處理任意精度的數字,建議將每個輸入讀取為字符串,然后逐個字符處理它,如下所示:
#include <cctype>
#include <iostream>
#include <string>
int main()
{
std::string s;
while (std::getline(std::cin, s)) {
// parse string
long sum = 0;
for (std::size_t i = 0; i < s.length(); ++i) {
if (std::isdigit(s[i]))
sum += s[i] - '0';
else
break;
}
std::cout << sum << std::endl;
if (sum < 10) break;
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.