c++ - 除了最右边数字为 "6"的任何整数输入都有效,但任何数字如 ...6 都会导致段错误,为什么?

标签 c++

我的名为“coinChange.cpp”的 C++ 程序报告了更改给定整数金额时不同数字的音符数。代码是

#include<iostream>
#include<string>
#include<sstream>

using namespace std;

int main()
{
     cout<<"please enter the amount: ";
     int amount;
     cin>>amount;
     int totalNoOfCoins=0;
     int coins[]= {100,50,20,10,5,1};
     int noOfCoins[sizeof(coins)]= {0};
     int counter=0;
     while(amount>0)
     {
          if(amount>coins[counter])
          {
                noOfCoins[counter]=amount/coins[counter];
                amount-=noOfCoins[counter]*coins[counter];
          }
          counter++;
     }
     string output="The amount can be changed by:\n";
     for(int i=0;i<sizeof(coins);i++)
     {
         if(noOfCoins[i]>0)
         {
             ostringstream oss;
             ostringstream oss1;
             oss<<coins[i];
             oss1<<noOfCoins[i];
            if(noOfCoins[i]>1) output+="\t\t\t"+oss1.str()+" nos of "+oss.str()+" taka notes \n";
            else output+="\t\t\t"+oss1.str()+" no of "+oss.str()+" taka note \n";
          }
    }
    cout<<output<<endl;
    return 0;
}

对于几乎任何整数(如 34、37829 等),结果都没有问题,但是当用户输入以 6 结尾的数字(如 6、x6、xx6、xxx6 等)时,问题就出现了。

最佳答案

我发现您的代码存在 3 个问题。

首先,显而易见的:

您在滥用 sizeof :

 int noOfCoins[sizeof(coins)]= {0};

这应该是:

 const int numCoins = sizeof(coins) / sizeof(coins[0]);
 int noOfCoins[numCoins]= {0};

然后从那里,您可以使用 numCoins对于其余代码:

 for(int i=0;i < numCoins; i++)

为什么sizeof(coins)的原因没用的是 sizeof返回大小以字节为单位

所以如果你有一个数组 6 int s,sizeof数组是 sizeof(int) * 6 ,即(假设您使用的是 4 字节整数)24。这超出了数组的范围,因此您会得到未定义的行为。


第二个问题:错误的 while() 循环条件:

while循环条件,你只测试 amount > 0 .但是如果 amount 是一个很大的值呢?你的while循环将增加 counter超出数组的范围,您将使用 counter作为 coins 中的索引数组,从而越界访问。

while 循环应该有这个条件:

while (amount > 0 && counter < numCoins)


问题三:正确铸币量的错误测试逻辑

你这样做:

if (amount > coins[counter])

但这是错误的。如果输入的金额只是 100 怎么办? ?您错过了使用上述条件的 100 钞票的支票。这只需要更改为:

if (amount >= coins[counter])

关于c++ - 除了最右边数字为 "6"的任何整数输入都有效,但任何数字如 ...6 都会导致段错误,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28575460/

相关文章:

c++ - Windows 7 上的奇怪行为 QT QSerialPort 不会更改串行 com 端口的设置

c++ - Xalan DLL 丢失

c++ - 如何随时停止使用 LIBXML SAX 解析 xml 文档?

python - Cython 扩展类 : How do I expose methods in the auto-generated C struct?

c++ - 为什么我需要像临时构造这样的复合文字来初始化我的 std::array 成员?

c++ - 递归函数问题和查找所有可能的路径

c++ - 查找所有在 Boost 中排序的

c++ - 运算符<< 重载隐藏其他

c++ - 为什么这个简单的 std::thread 示例不起作用?

c++ - 带有 opencv 的 qt 应用程序在关闭时失败 (0xC000004B)