C++ 使用带有 for 循环的枚举来填充浮点数组

C++ using enumerations with for loops to fill a float Array

我的运动是:

Write a program that gets the user's choice of color strength and transparency. Use a single enumeration for the colors and transparency - RED, GREEN, BLUE, ALPHA. Use a for loop that utilizes the enumeration set to iterate from RED up to ALPHA inclusive. Inside the for loop get the user to enter a value for each enumerated constant(i.e. a value for red, a value for blue, etc.) the values should be between 0.0 and 1.0 and stored in an array.

#include <string>
#include <iostream>

enum Difficulty
{
    RED,
    GREEN,
    BLUE,
    ALPHA

};

int main(int argc, char* argv[])
{

    char cColours[10][14] = { "RED", "GREEN", "BLUE", "ALPHA" };

    float fArray[4];
    int icounter = 0;

    while (icounter != 5)
    {

        std::cout << "For colour " << cColours[icounter] << " please enter a number ranging from 0.0 - 1.0 " << std::endl;
        std::cout << "press 10 to exit " << std::endl;


        for (int i = RED; i = ALPHA; i++)
        std::cin >> fArray[i];
        ++icounter;

    }

    system("pause");
    return 0;
}

根据评论,您想要获得一种颜色混合 (r,g,b,a)。你用嵌套数组什么都没有。

所以一个可能的代码:

#include <iostream>
#include <string>
#include <stdio.h>

enum ColorChannels {RED = 0, GREEN, BLUE, ALPHA, ALL_CHANNELS};
/*Every enumeration gives values to its elements. In default the first element is zero,
I illustrated this here. So ALL_CHANNELS (or difficulty if you want is equal with four,
which is the number of all channels - this will be useful in loop*/

int main(int argc, char* argv[])
{
     std::string names[ALL_CHANNELS];
     names[RED] = "RED"; //this is same to names[0]
     names[1] = "GREEN";
     names[BLUE] = "BLUE";
     names[3] = "ALPHA";
     /*I'm not sure if char sequences work. If work, use it. I prefer more the strings*/
     float colorArray[ALL_CHANNELS];

     for (int i = 0; i < ALL_CHANNELS; i++)
     {
          std::cout << "Enter " << names[i] << " value between 0.0 and 1.0: ";
          //For instance "Enter RED value between 0.0 and 1.0: "

          //and NOW your read one parameter. You made a nested loop for nothing
          std::cin >> colorArray[i];
          std::cout << "\n"; //for a new line
     }
     // all elements read

     system("pause");
     return 0;
}

尝试做一些改进练习,比如把颜色写回去;写出它更可能是红色、蓝色还是绿色;阅读更多颜色;等等