c++ - 如何创建正确的嵌套循环?

标签 c++

An array is given for 15 values. Take the absolute values for every three numbers in the array, going one after the other, and calculate the area of a triangle with sides, the values of which correspond to the taken numbers. Create a new array in which to enter the values of the resulting areas. Display all areas on the screen:


我知道如何计算面积等。但是我不知道如何组织正确的嵌套循环。
你能解释一下吗?
我的例子:
int numbers[15]{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
for (int i = 0; i < 5; i++) {
    for (int j = 0; j < 3; j++) {   
    }   
}

最佳答案

可以使用一个循环来完成。我认为,如果您查看了我的解决方案,则可以使用嵌套循环来实现。

double ans[10];
for(int i=0, j=0;i<15;i+=3, j++){
    double s=(double)(numbers[i]+numbers[i+1]+numbers[i+2])/2;
    double area = sqrt(s*(s-numbers[i])*(s-numbers[i+1])*(s-numbers[i+2]));
    ans[j]=area;
}
for(int i=0;i<5;i++) cout<<ans[i]<<endl;     

关于c++ - 如何创建正确的嵌套循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63214632/

相关文章:

c++ - 翻转 glReadPixels 的 RGBA 输出(C++ OpenGL)

c++ - 使用 std::map 和 std::pair 作为键并作为值列出

c++ - 编译错误声明我的 char vector 数组

c++ - Qt 右键单击​​ QListWidget 打开上下文菜单并删除项目

c++ - OpenCV SIFT 描述符关键点半径

c++ - 用户态和内核态共享内存

c++ - 图像处理-大纲

C++ 结构行为

c++ - 使用算法和/或函数库打印 vector 元素

python - 使用 ctypes 包装 DLL 函数