【问题标题】:c++ counting +ve, -ve and zeros from user's inputc++ 从用户输入中计算 +ve、-ve 和零
【发布时间】:2014-04-10 17:15:04
【问题描述】:

我想创建一个要求用户输入数字的程序。然后软件会统计有多少个正数、负数和零数。

请注意,我必须使用调用函数。

这是我到目前为止所做的,但仍然无法正常工作

#include <iostream>
using namespace std;

void counting(double, double);

int main()
{
    float count, P=0, i;
    cout<< "how many numbers you wanna enter?" << endl;
    cin >> count;
    do {

        cout << "enter your number: " << endl;
        cin >> i;

        counting(count, i);

        P++;
    }
    while (P<count);

    return 0;     
}

void counting(double count, double i)
{
    int positive_Count = 0;
    int negative_Count = 0;
    int zero_Count     = 0;
    int u;

    for (u=0; u <= count; u++)
    {
       if (i > 0)
       {
          positive_Count++;
       }
       else if (i < 0)
       {
          negative_Count++;
       }
       else if (i == 0)
       {
          zero_Count++;
       }  
    }

    cout  << "Count of positive elements = " << positive_Count << endl
      << "Count of negative elements = " << negative_Count << endl
      << "Count of zero     elements = " << zero_Count << endl;
}

【问题讨论】:

  • 你的逻辑有一个非常根本的缺陷。我建议您尝试调试它,甚至插入一些输出语句来跟踪它的实际操作。一旦你这样做了,你的问题就会非常明显。
  • doesn't work proper ... 在这里对一个问题含糊其辞。请先调试您的程序,并就某些您不理解或无法从 c++ 标准参考中解释的特定行为提出问题。
  • 为什么count 是一个浮点变量?是否允许用户输入 2.6 数字?
  • 我会从这段代码重新开始。它有太多缺陷无法恢复

标签: c++ function for-loop void do-while


【解决方案1】:

这是有严重缺陷的代码。 建议 -

  • 先读取所有数字,然后将它们复制到dynamically allocated array

  • 将该数组传递给counting function

  • loop 中的函数中迭代该数组并找到正数、负数和零的计数

【讨论】:

  • 使用std::vector,而不是动态分配的数组。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多