C ++偶数或奇数编号程序无法正常工作

时间:2016-04-20 18:00:17

标签: c++

我是C ++的新手,我正在做这里的练习:

http://www.learncpp.com/cpp-tutorial/32-arithmetic-operators/

我正在做测验2,它告诉我co创建一个从用户接收整数的程序,并打印出该整数的true是偶数。所以我创建了以下代码:

#include "stdafx.h"
#include <iostream>

int getInteger()
{
    std::cout << "Insert an integer" << "\n";

    int8_t x;

    std::cin >> x;

    return x;
}

bool isEven(int8_t x)
{
    bool b;
    b = false;

    std::cout << x % 2 << "\n";

    if(x%2 == 0)
        {
            b = true;
        }

    return b;
}

void printResult(bool b)
{
    std::cout << std::boolalpha;
    std::cout << b << "\n";
}

int main()
{
    int8_t x;
    x = getInteger();

    bool b;
    b = isEven(x);

    printResult(b);

    return 0;
}

所以,这就是问题所在。除非我错过了什么,否则这应该有效,对吧?它确实如此,但仅适用于从0到10输入的整数。出于某种原因,如果我输入10或12,它会打印错误,但它可以在2,4,6和8下正常工作。为什么会发生这种情况?

4 个答案:

答案 0 :(得分:2)

您有以下代码:

int8_t x;
std::cin >> x;

int8_t只是您平台的char的别名,而std::istream的别名是char,因为参数输入一个字符,而不是整数。所以解决方案是使用类型int,你应该从头开始使用它,因为在这种情况下根本没有理由使用int8_t

答案 1 :(得分:1)

此函数返回的类型与它应返回的类型不同:

int getInteger()
{
    std::cout << "Insert an integer" << "\n";

    int8_t x;

    std::cin >> x;

    return x;
}

int应该可以正常工作而不是int8_t,并在此处查看原因Documentation

答案 2 :(得分:0)

如你所知getInteger()需要字符文本翻译输入,而不是数字。,因为int8_t实际扩展为char

要解决此问题,请在第1位采用整数并转换为int8_t类型:

int getInteger()
{
    std::cout << "Insert an integer" << "\n";

    int x; // <<<<
    std::cin >> x;
    return x;
}
x = (int8_t)getInteger();

答案 3 :(得分:0)

Alex在learncpp.com上指定使用固定宽度整数更好的原因是因为程序的结果在不同编译器上编译时不会发生变化。对于像charint这样的非固定宽度整数类型,情况并非如此,因为类型的大小会因编译器而异。正如@Slava指出的那样,int8_tchar的固定宽度整数类型,因此两者都用于只在内存中存储单个字符的变量。

只要程序可以在不同的编译器或机器中使用,就使用固定宽度整数,并且结果与编译器和平台无关是很重要的。因为程序要求任何整数的用户输入,要使用固定宽度的整数,最好使用int32_tint8_t和&#39; char&#39;适合获取数字(即0-9)。 int16_t适用于-2 ^ 16/2(等于-2 ^ 15)和2 ^ 15-1(即介于-32 768和32 767之间)的整数。 &#39; int32_t&#39;适用于-2 ^ 31和2 ^ 31-1之间的整数(即-2 147 483 648和2 147 483 647之间)。

正如亚历克斯后来在5.10 — std::cin, extraction, and dealing with invalid text input中解释的那样,处理所有可能的无效用户输入非常重要。

以下是一些可以使用的更新代码,处理无效的用户输入,并循环询问用户是否要检查另一个数字是偶数还是奇数,这样做:

&#13;
&#13;
// StackOverflow C++ Even or Odd number program.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream> // for cin and cout
//include <cmath>	// pow is no longer used and is commented out below.
#include <cstdint> // std::int32_t

// I changed the variable output for the function to int32_t, since that is the type being returned.
std::int32_t getInteger()
{
	/* If you don't understand some parts, like do-while loops and
	handling invalid user input, come back to it after learning it,
	and just focus on what you can understand.
	*/

	// Use int32_t since the user input could potentially be a very large number.
	std::int32_t x{ 0 };
	bool notInt32t = 1;
	bool cinFail{1};
	do
	{
		// Don't use an '/n' character when getting user input, it makes more sense to get it on the same line as the prompt.
		std::cout << "Enter an integer: ";

		std::cin >> x;

		cinFail = std::cin.fail();

		if (cinFail)
		{
			std::cin.clear();
			std::cin.ignore(32767, '\n');
			std::cout << "Oops, that input is invalid. This may be because you entered a number larger \n";
			std::cout << "than 2147483647 (which equals 2^31-1), or less than -2147483648 (which equals -2^31); \n";
			std::cout << "or you did not enter an integer only. Please try again.\n";
		}
		// remove any extraneous input, which would otherwise be left in the buffer, causing unexpected results.
		else
			std::cin.ignore(32767,'\n'); 

		/*Commented out because this will not work, it will fail to extract. Left in the code for education purposes.
		notInt32t = ((x > (pow(2.0, 31.0) - 1)) || (x < -pow(2.0, 31.0)) || !(x % 1 == 0));
		if (notInt32t)
			std::cout << "Oops, you entered incorrectly!\n";
		*/
	} while (cinFail);

	return x;
}

bool isEven(std::int32_t x)
{
	bool isEven;

	isEven = (x % 2 == 0) ?(true):(false);

	return isEven;
}

/* I have commented this out and rewrote it, as it is ambiguous.
void printResult(bool b)
{
	std::cout << std::boolalpha;
	std::cout << b << "\n";
}*/

void printIsEven()
{
	auto x = getInteger();

	if (isEven(x))
		std::cout << x << " is an even integer.\n";
	else
		std::cout << x << " is an odd integer.\n";
}
void printIsEvenLoop()
{
	std::int8_t yOrN{};
	bool isLoop{ true };
	bool cinFail{ false };
	bool isYOrN{ false };
	while (isLoop)
	{
		do
		{
			std::cout << "Would you like to check whether another integer is even or odd?\n";
			std::cout << "Enter y or n (yes or no): ";
			std::cin >> yOrN;

			cinFail = std::cin.fail();

			if (cinFail)
			{
				std::cin.clear();
				std::cin.ignore(32767, '\n');
				std::cout << "Oops, that input is invalid! Please try again.\n";
			}
			// remove any extraneous input, which would otherwise be left in the buffer, causing unexpected results.
			else
				std::cin.ignore(32767, '\n');

			isYOrN = ((yOrN == 'y' || yOrN == 'n'));
			if (!isYOrN)
				std::cout << "Oops, you entered incorrectly! Please try again.\n";

		} while (cinFail || !isYOrN);

		if (yOrN == 'y')
		{
			isLoop = true;
			printIsEven();
		}
		else
			isLoop = false;
	}
	
}
int main()
{
	printIsEven();
	
	printIsEvenLoop();

	return 0;
}
&#13;
&#13;
&#13;