我还在努力学习算法,我有一个功课。我必须输出
Sum of : 1/2 + 1/4 + 1/6 - 1/8 + 1/10 + 1/12 Result : 0.975
但我的程序输出
Sum of : 1/2 + 1/4 + 1/6-1/8 + 1/10 + 1/12 Result : 0.975
我不知道如何制作空间negative sign
,如果我使用cout,则会显示两次负号。
我的计划
#include <iostream>
#include <math.h>
using namespace std;
int main ()
{
int i ,sign, p, q, n;
double x , S;
S=0;
cout << "Sum of :";
for (i=1; i <= 6; i++)
{
if ( (i % 4 == 0) && ( i > 1 ) ) // to make condition where the number become negative
{
sign = -1;
}
if ( ( i % 4 != 0 ) && ( i > 1 ) ) // to make condition where the number become positive
{
sign = 1;
cout << " + ";
}
if ( i == 1 ) // to prevent 1st number not show " + " symbol
{
sign =1;
}
p = sign*1;
q = ( 2 * ( i - 1 ) ) + 2;
cout << p << "/" << q;
x = ( 1.0 * p / q );
S = S + x;
}
cout << "\n" << S;
}
我意识到我的程序有太多可以避免的操作,你能帮我把它变得更有效吗?
答案 0 :(得分:0)
所以你的
cout << p << "/" << q;
如果p为负数,将始终具有该格式。 相反(此解决方案旨在简单)
if(p < 0) {
cout << " - " << p*-1 << "/" << q;
} else {
cout << p << "/" << q;
}
应该这样做。
答案 1 :(得分:0)
如果您希望按照主题中的说明使用递归,那么您也可以参考。
static void recurse(int i, int limit){
int sign = 0, p, q, n;
double x, S;
S =0;
if (i == 1) // to prevent 1st number not show " + " symbol
{
sign = 1;
cout << "Sum of : ";
}
else if (i< 1 || i> limit){
return ;
}
else {
sign = (i % 4 == 0) ? -1 : 1;
if (sign > 0){
cout << " + ";
}
else {
cout << " - ";
}
}
p = 1;
q = ( 2 * ( i - 1 ) ) + 2;
cout << p << "/" << q;
x = ( 1.0 * p / q );
S = S + x;
recurse(i+1, limit);
}
使用以下方式致电:
int main ()
{
recurse(1, 6);
cout << "\n";
}