【问题标题】:Why is my parallel array displaying random values?为什么我的并行数组显示随机值?
【发布时间】:2020-02-28 19:15:44
【问题描述】:

我应该使用一个并行数组来根据添加的插件显示一杯咖啡的量。原来的一杯咖啡是2美元。我主要对如何输出正确的结果感到困惑。目前,它将输出“Order total is2”。我错过了什么?

// JumpinJava.cpp - This program looks up and prints the names and prices of coffee orders.  
// Input:  Interactive
// Output:  Name and price of coffee orders or error message if add-in is not found 

#include <iostream>
#include <string>
using namespace std;

int main()
{
   // Declare variables.
    string addIn;     // Add-in ordered
    const int NUM_ITEMS = 5; // Named constant
    // Initialized array of add-ins
    string addIns[] = {"Cream", "Cinnamon", "Chocolate", "Amaretto", "Whiskey"}; 
    // Initialized array of add-in prices
    double addInPrices[] = {.89, .25, .59, 1.50, 1.75};
   bool foundIt = false;     // Flag variable
   int x;                // Loop control variable
   double orderTotal = 2.00; // All orders start with a 2.00 charge

   // Get user input
   cout << "Enter coffee add-in or XXX to quit: ";
   cin >> addIn;

   // Write the rest of the program here. 
        for(int i = 0; i < NUM_ITEMS; i++){
            if (addIns[i] == (addIn))
            foundIt = true;
                   if (foundIt)
                 {
                    x = orderTotal + addInPrices[i];
                    cout << "Order Total is" << x << endl;
                    }
        else cout <<"Sorry, we do not carry that."<< endl; 
        }

   return 0;
} // End of main() 

【问题讨论】:

  • 您是否尝试使用调试器逐行执行代码?
  • x 是一个int,它将截断双精度数。我怀疑这是故意的? (您的评论也说“流量控制变量”,这似乎也不准确)。推荐阅读:How to debug small programs
  • 问题是它正在显示输出。所以我没有收到任何错误。我相信是输出搞砸了,我只是不知道该怎么说
  • 并行数组在哪里?
  • Double to int 截断不是错误(尽管一些编译器对此发出警告)。所以是的,你会得到输出。 for example

标签: c++ parallel-arrays


【解决方案1】:

在这一行:

x = orderTotal + addInPrices[i];

您正在将x(一个int 值)设置为2.00 + 0.25,对吗?您的编译器可能会在此处警告您可能会丢失精度。 整数 值只能包含整数:1、2、3 等。如果您尝试将其设置为 2.25 之类的浮点数,它将被截断(截断小数点)而离开只有整数部分。所以x = 2.25的结果就是x中2的值,和你的输出是一致的。

在你的作业模板中,你的老师在x的声明旁边写了这条评论:

int x;                // Loop control variable

我似乎很清楚,x 的意图是您放入 for 循环中的内容,即控制循环发生次数和结束时间的变量。您选择创建一个新变量i。这也可以解释为什么 x 没有被初始化为任何东西 - 如果你按照预期的方式进行初始化,初始化将在 for 循环中发生。

试试这个:不要使用x 来存储新价格,只需将插件价格添加orderTotal,这样它就始终是最新的并且具有正确的价值。这样,您根本不需要为此使用x,而是可以在 for 循环中使用它。然后,您将在输出中打印 orderTotal 而不是 x

【讨论】:

  • 喜欢这个? totalPrice = orderTotal + addInPrices[i];当我这样做时,它只是说未声明总价格
  • 抱歉,totalPrice 打错了。你得到的变量是orderTotal。我所说的重点是,您应该简单地重复使用相同的变量来跟踪订单总额的变化。我已经编辑更正了。
  • 哦,好的。谢谢!
猜你喜欢
  • 2020-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多