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

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

本文关键字:填充 数组 枚举 使用 for 循环 C++      更新时间:2023-10-16

我的练习是:

编写一个程序,获取用户对颜色强度和透明度的选择。对颜色和透明度使用单个枚举 - REDGREENBLUEALPHA。使用利用枚举集从RED循环到ALPHA(含(循环for循环。在for循环中,让用户为每个枚举常量输入一个值(即红色值,蓝色值等(,这些值应该在0.01.0之间,并存储在数组中。

#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;
}

尝试对锻炼做一些改进,比如写回颜色;写出它是否更有可能是红色,蓝色或绿色;阅读更多颜色;等等。