c++ 我的偶数奇程序给出奇数输出为每10位偶数

ha5z0ras  于 2023-06-25  发布在  其他
关注(0)|答案(2)|浏览(162)

我创建了奇偶程序来检测奇数和偶数。它是工作正常的所有数字小于10位,但当我给予输入222222222在代码,它给输出奇数,但如何?

  1. #include<iostream>
  2. using namespace std;
  3. int main(){
  4. int a;
  5. cin>>a;
  6. if(a%2==0){
  7. cout<<"This is EVEN";
  8. }
  9. else{
  10. cout<<"This is ODD";
  11. }
  12. return 0;
  13. }

我试着给出222222222的输入,并期望输出偶数,但它给出奇数。

6yt4nkrj

6yt4nkrj1#

我猜您使用的是32位,因此,整数范围从2 147 483 647到-2 147 483 648。使用其他数据类型(例如long long)或切换到64位。
编辑:正如@wohlstad在他的评论中所说,切换到64位可能无法解决问题。使用另一种数据类型是可行的方法。

db2dz4w8

db2dz4w82#

问题是2222222222大于int(即* * 2147483647**)。因此,它会导致溢出并导致错误的输出。
有几种方法可以解决这个问题。最简单的方法是使用long long,它的范围很大(在32位和64位的X86变体中,最大可达9223372036854775807)。
像这样:

  1. #include <iostream>
  2. #include <limits>
  3. int main()
  4. {
  5. long long int a;
  6. std::cout << "Enter a number in range "
  7. << 0
  8. << " to "
  9. << std::numeric_limits<decltype( a )>::max()
  10. << ": ";
  11. std::cin >> a;
  12. if ( a % 2 == 0 )
  13. std::cout << "This is EVEN\n";
  14. else
  15. std::cout << "This is ODD\n";
  16. }

样本输出:

  1. Enter a number in range 0 to 9223372036854775807: 2222222222
  2. This is EVEN

另一种方法是将输入作为std::string,然后检查其最低有效位是否为偶数。
这是一个例子:

  1. #include <iostream>
  2. #include <locale>
  3. #include <string>
  4. #include <string_view>
  5. bool is_number( const std::string_view str )
  6. {
  7. const auto loc { std::cout.getloc() };
  8. for ( const char c : str )
  9. if ( !std::isdigit( c, loc ) ) return false;
  10. return true;
  11. }
  12. int main()
  13. {
  14. std::string a;
  15. do
  16. {
  17. std::cout << "Enter a number as big as you want: ";
  18. std::cin >> a;
  19. }
  20. while ( !is_number( a ) );
  21. if ( a.back() % 2 == 0 )
  22. std::cout << "This is EVEN\n";
  23. else
  24. std::cout << "This is ODD\n";
  25. }

样本输出:

  1. Enter a number as big as you want: 2222222222222222222222222222222222222222222222222222222222222222222222222222222222229
  2. This is ODD

现在请注意,在上面的解决方案中,条件if ( a.back() % 2 == 0 )可能看起来很奇怪,因为a.back()返回一个char,然后我们对它应用模(%)运算符。这是有效的,因为偶数十进制数字的ASCII值也是偶数(例如“0”== 48,“2”== 50,“4”== 52)。所以最后保证结果是正确的。

展开查看全部

相关问题