简体   繁体   English

无论我用作输入,输出全为零

[英]whatever i use as inputs, outputs are all zeros

This is a question i am working on: 这是我正在研究的一个问题:

  • Prompt the user to enter five numbers, being five people's weights. 提示用户输入五个数字,即五个人的体重。 Store the numbers in a vector of doubles. 将数字存储在双精度向量中。 Output the vector's numbers on one line, each number followed by one space. 在一行上输出矢量的数字,每个数字后跟一个空格。
  • Also output the total weight, by summing the vector's elements. 通过对向量的元素求和,还输出总权重。

  • Also output the average of the vector's elements. 还输出向量元素的平均值。

  • Also output the max vector element. 同时输出最大向量元素。 So far this is the code i have 到目前为止,这是我拥有的代码

     #include <iostream> #include <vector> using namespace std; int main() { const int NEW_WEIGHT = 5; vector<float> inputWeights(NEW_WEIGHT); int i = 0; float sumWeight = 0.0; float AverageWeight = 1.0; int maxWeight = 0; int temp = 0; for (i = 0; i < NEW_WEIGHT; i++){ cout << "Enter weight "<< i+1<< ": "; cout << inputWeights[i]<< endl; cin>> temp; inputWeights.push_back (temp); } cout << "\\nYou entered: "; for (i =0; i < NEW_WEIGHT- 1; i++) { cout << inputWeights.at(i)<< " "; } cout<< inputWeights.at(inputWeights.size() - 1) << endl; for (i =0; i < NEW_WEIGHT; i++){ sumWeight += inputWeights.at(i); } cout <<"Total weight: "<< sumWeight<< endl; AverageWeight = sumWeight / inputWeights.size(); cout <<"Average weight: "<< AverageWeight<< endl; maxWeight= inputWeights.at(0); for (i =0; i < NEW_WEIGHT- 1; i++){ if (inputWeights.at(i) > maxWeight){ maxWeight = inputWeights.at(i); } } cout<< "Max weight: "<< maxWeight << endl; return 0; } 

When i run this code, whatever inputs i use(for the cin>>(...)), i get all zero's as output and i do not know why. 当我运行此代码时,无论使用什么输入(用于cin >>(...)),我都会得到全零的输出,但我不知道为什么。 can i get some help please. 请给我一些帮助。

update cleaned up the code a little by getting rid of the cout<< inputWeights[i]<< endl; 更新通过消除cout << inputWeights [i] << endl来稍微清理代码
and by adjusting vector inputWeights; 并通过调整向量inputWeights; at the beginning of the program.But the outputs are still not exactly what they are supposed to be. 在程序开始时。但是输出仍然不完全是应该的。 Instead, only the first 2 inputted values make it as outputs. 取而代之的是,只有前两个输入值将其作为输出。 Any reason why? 有什么原因吗? thanks 谢谢

update this is the right or correct code. 更新这是正确或正确的代码。 Hope it helps someone in future. 希望以后能对某人有所帮助。

#include <iostream>
#include <vector>

using namespace std;

int main() {
   const int NEW_WEIGHT = 5;
   vector <float> inputWeights;
   int i = 0;
   float sumWeight = 0.0;
   float AverageWeight = 1.0;
   float maxWeight = 0.0;
   float temp = 0.0;

   for (i = 0; i < NEW_WEIGHT; i++){
      cout << "Enter weight "<< i+1<< ": "<< endl;
      cin>> temp;
      inputWeights.push_back (temp);

      }


      cout << "\nYou entered: ";

   for (i =0; i < NEW_WEIGHT- 1; i++){

      cout << inputWeights.at(i)<< " ";
   }
      cout<< inputWeights.at(inputWeights.size() - 1) << endl;

    for (i =0; i < NEW_WEIGHT; i++){

       sumWeight += inputWeights.at(i); 

      }
   cout <<"Total weight: "<< sumWeight<< endl;

       AverageWeight = sumWeight / inputWeights.size();

   cout <<"Average weight: "<< AverageWeight<< endl;

      maxWeight= inputWeights.at(0);
    for (i =0; i < NEW_WEIGHT- 1; i++){
       if (inputWeights.at(i) > maxWeight){
          maxWeight = inputWeights.at(i);
          }
    }

   cout<< "Max weight: "<< maxWeight << endl;

   return 0;
}

You're making a vector of size 5: 您正在制作大小为5的vector

const int NEW_WEIGHT = 5;
vector<float> inputWeights(NEW_WEIGHT);

// == 0, 0, 0, 0, 0

Then, in your input loop, you're adding new values to the end: 然后,在输入循环中,将新值添加到末尾:

inputWeights.push_back (42);

// == 0, 0, 0, 0, 0, 42

Then you're outputting the first five elements which were always zero. 然后,您将输出始终为零的前五个元素。

You need to choose one thing or the other: either set the size of the vector at the start of the program, or grow the vector with push_back for as long as there's input. 您需要选择另一项:要么在程序开始时设置矢量的大小,要么在有输入的情况下使用push_back增大矢量。 Both are valid options. 两者都是有效的选项。

You can clean up your code and fix the problems by adopting modern C++ (as in, C++11 and later) idiom. 您可以采用现代C ++(如C ++ 11及更高版本)习惯用法来清理代码并解决问题。 You don't need to fill your code with for(int i = 0; i < something; i++) any more. 您无需再用for(int i = 0; i < something; i++)填充代码。 There's a simpler way. 有一种更简单的方法。


// Size fixed in advance:
vector<float> weights(NUM_WEIGHTS);

for (auto& weight : weights) { // note it's `auto&`
  cout << "\nEnter next weight: ";
  cin >> weight; // if it was plain `auto` you'd overwrite a copy of an element of `weight`
}

// Size decided by input:
vector<float> weights; // starts empty this time

cout << "Enter weights. Enter negative value to stop." << endl;
float in;
while (cin >> in) {
  if(in < 0) {
    break;
  }
  weights.push_back(in);
}

In either case, you can then play with the filled vector using another range-based for : 无论哪种情况,都可以使用另一个基于范围的for来填充的矢量:

cout << "You entered: ";
for (const auto& weight : weights) {
  cout << weight << " ";
}

You'll also need to remove the cout << inputWeights[i] << endl; 您还需要删除cout << inputWeights[i] << endl; line from your input loop if you resize the vector during input - as written you'd be reading elements which don't exist yet, and will probably get an array-index-out-of-bounds exception. 如果在输入过程中调整矢量的大小,则从输入循环中移出一行-如所写,您将读取尚不存在的元素,并且可能会得到array-index-out-of-bounds异常。

When you create define your inputWeights you are putting 5 items into it with default values. 创建定义输入权重时,您将使用默认值将5个项目放入其中。

vector<float> inputWeights(NEW_WEIGHT);

Change it to be just 改变它只是

vector<float> inputWeights;

And get rid of this line in your code or comment it out 并摆脱代码中的这一行或将其注释掉

cout << inputWeights[i]<< endl; 

This is what you are looking for from the requirements of your program. 这是您从程序需求中寻找的东西。

#include <vector>
#include <iostream>

int main() {
    std::vector<double> weights;

    double currentWeight = 0.0;
    const unsigned numberOfWeights = 5;
    std::cout << "Enter " << numberOfWeights << " weights" << std::endl;
    unsigned i = 0;
    for ( ; i < numberOfWeights; ++i ) {
        std::cin >> currentWeight;
        weights.push_back( currentWeight );
    }

    std::cout << "These are the weights that you entered: " << std::endl;
    for ( i = 0; i < weights.size(); ++i ) {
        std::cout << weights[i] << " ";
    }
    std::cout << std::endl;

    double totalWeight = 0.0;
    std::cout << "The total of all weights is: ";
    for ( i = 0; i < weights.size(); ++i ) {
        totalWeight += weights[i];
    }
    std::cout << totalWeight << std::endl;

    std::cout << "The average of all the weights is: " << (totalWeight / numberOfWeights) << std::endl;

    std::cout << "The max weight is: ";
    double max = weights[0];
    for ( i = 0; i < weights.size(); ++i ) {
        if ( weights[i] > max ) {
            max = weights[i];
        }
    }
    std::cout << max << std::endl;

    return 0;
}

The culprit to your problem for seeing all 0s as output is coming from these two lines of code: 看到全0为输出的问题的罪魁祸首来自以下两行代码:

const int NEW_WEIGHT = 5;
vector<float> inputWeights(NEW_WEIGHT);

which is the same as doing this: 这与执行此操作相同:

vector<float> inputWeights{ 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };

you are then looping through up to 5 elements using NEW_WEIGHT when it would be easier to use inputWeights.size() when traversing through containers. 然后,当遍历容器时更容易使用inputWeights.size()时,您将使用NEW_WEIGHT循环访问多达5个元素。

Edit - Condensed Version 编辑-压缩版

#include <vector>
#include <iostream>

int main() {
    std::vector<double> weights;

    double currentWeight           = 0.0;
    const unsigned numberOfWeights = 5;
    unsigned i = 0;

    std::cout << "Enter " << numberOfWeights << " weights" << std::endl;
    for ( ; i < numberOfWeights; ++i ) {
        std::cin >> currentWeight;
        weights.push_back( currentWeight );
    }

    double totalWeight = 0.0;
    double max         = weights[0];
    std::cout << "These are the weights that you entered: " << std::endl;
    for ( i = 0; i < weights.size(); ++i ) {
        std::cout << weights[i] << " ";   // Print Each Weight
        totalWeight += weights[i];        // Sum The Weights

        // Look For Max Weight
        if ( weights[i] > max ) {
            max = weights[i];
        }
    }
    std::cout << std::endl;

    std::cout << "The total of all weights is: " << totalWeight << std::endl;
    std::cout << "The average of all the weights is: " << (totalWeight / numberOfWeights) << std::endl;
    std::cout << "The max weight is: " << max << std::endl;

    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当我使用regasm时,是否将所有参数都输入为输入? 可以改变吗? - When I use regasm, all parameters are typed as inputs? Can that be changed? 原始输入后,我一直得到零 - I keep getting zeros when after my original inputs 如何在 C++ 中打印多个输入和输出? - How do I print multiple inputs and outputs in C++? C++ 中的多个输入和输出 - Multiple inputs and outputs in C++ C++ 如何将我认为是字符串的内容转换为 int? 尝试使用 stoi,但会使用任何有效的方法 - C++ How to convert what I thought was a string into an int? Trying to use stoi, but will use whatever works 我可以将指针作为指向类的指针传递,以便我可以使用分配给类中指针的任何内容吗? - Can I pass a pointer as a pointer to a class, so I can use the whatever is assigned to the pointer in the class? 我必须编写一个 c++ 代码,在字符串中输入一个名称并以不同的顺序输出它 - I have to write a c++ code that inputs a name in string and outputs it in a different order 将 void* 转换为任何内容时,我应该使用 static_cast 还是 reinterpret_cast - Should I use static_cast or reinterpret_cast when casting a void* to whatever 我得到的是我所有的输出,而不仅仅是一个 - I am getting all of my outputs instead of just one 在C ++中,如何在列表中的每个连续零运行中删除除x之外的所有零? - In C++, how can I delete all zeros except for x of them in every run of consecutive zeros within a list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM