我的C代码有什么问题?循环中的东西?

时间:2014-03-30 04:17:42

标签: c arrays while-loop

我遇到了一个我正在做的小程序的问题,我希望它能够获得美元汇率并换成不同的货币,它正在工作但是在它工作后打印了很多乱码... 看看我得到的结果的屏幕截图: enter image description here

2 个答案:

答案 0 :(得分:1)

更改

while ((quintity[Index]) != '\0') {
  Index++;

for (Index = 1; Index < inputIndex; Index++) {

再试一次。

答案 1 :(得分:1)

打印数据时的循环条件:

while (quintity[Index] != '\0') {

相信这样一个事实:当从用户获取值时,您的输入循环从未实际在数组中放置零。 那是为什么循环在数据的(明显)结束后继续进行。

您可以在输入循环后立即执行此操作:

while (scanf ("%f", &input) != '\0') {
    quintity[inputIndex] = input;
    inputIndex++;
}
quintity[inputIndex] = 0;  // add this

虽然请记住,如果您实际输入零作为输入值,则意味着您无法获得合理的输出。

使用endinel端环检测方法。即使您输入零,长度方法也会起作用。我的意思是,在打印数据时使用inputIndex作为Index的限制值:

while (Index < inputIndex) {

总之,我认为以下代码是更好的解决方案,因为:

  1. scanf会返回已转换的项目数,因此您应该继续进行转换,而不是在它为零时(scanf实际返回-1某些错误,你
  2. 您应该在打印循环中使用inputIndex作为index的限制器。这比基于哨兵的检查更有效,因为它允许输入零金额。
  3. 如果inputIndex达到MAX,您真的不应该尝试存储值。这使得代码成熟,可以缓冲溢出。
  4. 考虑到所有这些,我会把它转换成类似的东西:

    while ((inputIndex < MAX) && (scanf ("%f", &input) == 1))
        quintity[inputIndex++] = input;
    
    for (Index = 1; Index < inputIndex; Index++) {
        HamaraGate = quintity[0] * quintity[Index];
        :
        sumDollar += HamaraGate;
    }