C++中的数学计算

Mathematical calculation in C++

本文关键字:计算 C++      更新时间:2024-03-28

我想用这个公式写一个函数!

列出你的曾祖父母去世的年龄。

将每个数字相乘。

把它们加在一起。

取结果的平方根。

除以二。

这是一个例子:

predictAge(65, 60, 75, 55, 60, 63, 64, 45) === 86

这是我写的代码:

#include <math.h>
#include <iostream>
#include <vector>
#include <cmath>
int predictAge(std::vector<int> ages)
{
for(int i = 0; i < ages.size(); i++) {
int Produc = ages[i] * ages[i];
int Sum = Produc + Produc;
int Squar = sqrt(Sum);
int Final = Squar / 2;
std::cout << Final << "n";  

} 
}
int main() {
std::cout << predictAge({65, 60, 75, 55, 60, 63, 64, 45});
return 1;
}

有人能帮忙吗?

类似于:

int predictAge(std::vector<int> ages)
{
int Sum = 0;
for(int i = 0; i < ages.size(); i++) {
int Produc = ages[i] * ages[i];
Sum += Produc;  
}
return sqrt(Sum) / 2;
}

您应该注意输入数据检查和错误处理。

如果你拼写出了正确的算法,你就是无法正确实现它。您希望RSS(平方根(除以std::vector中所有年龄中的两个。既然RSS是一种常见的算法,为什么不写一个函数来计算所有值的RSS,然后将返回值除以2来完成你的算法呢。

您可以实现如下:

#include <iostream>
#include <vector>
#include <cmath>
double rss (std::vector<int>& ages)
{
double sum = 0.;

for (const auto& a : ages)
sum += a * a;

return sqrt (sum);
}
int main (void) {

std::vector<int> ages { 65, 60, 75, 55, 60, 63, 64, 45 };

std::cout << static_cast<int>(rss(ages) / 2.) << 'n';
}

(注意:因为需要一个整数值,所以将返回值除以2强制转换为int。如果需要浮点结果,可以删除强制转换(

函数中for循环上方是基于范围的循环(由于C++11(

示例使用/输出

$ ./bin/rss_ages
86

仔细看看,如果你还有问题,请告诉我。