【问题标题】:Error in program to find the Armstrong numbers between intervals given by the user [closed]在用户给出的区间之间查找阿姆斯壮数的程序出错[关闭]
【发布时间】:2019-03-29 09:40:35
【问题描述】:

错误:

//计数(变量)未声明!错误。

但我已经宣布了。这是一个程序,用于计算用户给定的区间内的 Armstrong 位数。它将继续运行,直到间隔中至少有一个 Armstrong 数。为此,我使用了 Do-While 循环。

C++:

#include<iostream>
#include<cmath>  

using namespace std;

//Function to check if the number is an Armstrong number
bool Armstrong(int n) {
    int number, original, remainder, result = 0, k = 0;
    original = n;
    //Calculating the number of digits
    while (original != 0) {
        original /= 10;
        ++k;
    }

    original = n;

    while (original != 0) {
        remainder = original % 10;
        result += pow(remainder, k);
        original /= 10;
    }

    if (result == n)
        return true;
    else
        return false;
}

//Checking Armstrong in the interval
int main() {
    do {
        int start, stop, n, i = 1;
        std::cout << "Enter Starting Point: ";
        std::cin >> start;
        std::cout << "Enter Stop Point: ";
        std::cin >> stop;
        n = start;
        int count = 0; //printing the numbers in the interval
        for (; start <= stop; start++) {
            if (Armstrong(start)) {
                std::cout << "Armstrong Number " << i << " : " << start;
                count++;
                i++;
            }
            n--;
        }
        //It is showing the error here. "Count not Declared"
    }
    while (count == 0);
}

【问题讨论】:

  • 欢迎来到 Stack Overflow。请阅读the help pages,获取the SO tour,了解how to ask good questions,以及this question checklist。最后,在询问有关构建错误的问题时,请将 fullcomplete 错误输出复制粘贴(作为文本)到问题本身。
  • 关于您的问题的提示:请记住,范围以 } 结尾。块内定义的变量在结束 } 之后不存在。
  • 请确保您发布准确的代码和错误消息。您的代码中没有Count。细节很重要,因为如果您声明 count,则仍然没有声明 Count
  • 函数名应该小写。你应该声明一个索引,所以 start 在循环中不会改变

标签: c++ scope do-while


【解决方案1】:

问题是您在do-while 循环内声明了int count;,因此您无法在循环条件中检查它。将其移至循环外:

int count = 0;
    do {
        int start, stop, n, i = 1;
        ...
    } while (count == 0);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-30
    • 1970-01-01
    • 2021-04-03
    • 1970-01-01
    相关资源
    最近更新 更多