我的名为“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/