c++ - 可能操作错误,随机个位数输出

标签 c++

我为一个要求正数的类编写了这个程序,并根据该数字执行计算。上周我从堆栈人员那里得到了一些很大的帮助,但我的教授要求我重写它并简化我的代码。我已经这样做了,现在数学计算不正确。我已经运行了调试器,但我没有看到传递的值在哪里不正确。此外,所有数字都未通过“if (number > 0)”测试。

即使我收到构建成功的消息,它会不会是编译错误?

提前致谢!

这是代码。

#include <iostream>
#include <string>
#include <fstream>  
#include <iomanip>
#include <stdexcept>
#include <cstdlib>

using namespace std;

int main ()
{
    system ("color F0");

    int number, countIf = 0, countWhile = 0, countDo = -1, h = 0, i = 0, x = 0, y = 0;
    char repeat = 'y';

    do {

        cout << "Please enter a positive integer or zero to quit: ";
        cin >> number;
        x = number, y = number;
        cin.ignore();

        if (number < 0) 
            cout << "Error: The integer entered was either not positive or a zero.\n" << endl;

        else if (number > 0)
        {
            if (number%2 == 0 && number%5 == 0)
                for (y%5; countIf <= y; countIf +=5)
                    {
                        i = y / 10;
                        i += countIf;
                        cout << countIf << " ";
                    }

            else if 
                (countWhile < x && number%2 == 0) 
                    {
                        countWhile += 2;
                        cout << countWhile << " ";
                    }

            else 
                {
                    countDo +=2;
                    cout << countDo << " ";
                }
        } 

            cout << "\n\nDo you wish to continue? (Y or N): ";
            cin >> repeat;
}
        while (number != 0 && repeat == 'y' || repeat == 'Y');



    //cout << "\nThanks for playing!" << endl;
    system ("pause");
    return 0;


}

输出应该类似于:

enter image description here

我得到的是:

enter image description here

最佳答案

我这样修改了你的代码:

        else if
            (countWhile < x && number%2 == 0)
                {
                    for(countWhile+=2; countWhile<x; countWhile+=2)
                        cout << countWhile << " ";
                }

        else
            {
                    for(countDo+=2; countDo<x; countDo+=2)
                        cout << countDo << " ";
            }

我得到如下输出:

Please enter a positive integer or zero to quit: 82
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80

Do you wish to continue? (Y or N): y
Please enter a positive integer or zero to quit: 75
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73

希望这对您有所帮助。

关于c++ - 可能操作错误,随机个位数输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15891928/

相关文章:

c++ - WinApi如何获取表单中事件元素的句柄

c++ - API 更改时函数参数的常量正确性

C++检查是否传递了指针,否则创建一个?

c++ - 有谁知道为什么 Visual Studio 2015 Update 2 中使用 native c++ 的智能感知如此慢?

c++ - 避免C++虚拟继承

c++ - 为什么标准区分直接列表初始化和复制列表初始化?

c++ - 试图使用链接列表实现冒泡排序,但不起作用

c++ - 内联 asm 将值写入内存

c++ - boost lambda 或 phoenix 问题:使用 std::for_each 对容器的每个元素进行操作

c++ - 是否有静态分析器可以检查 C/C++/Objective-C 中的局部变量重新分配?