我需要帮助我的代码!对我来说它看起来很好但是它不起作用。我已经尝试过,但我无法弄清楚什么是错的。
我还需要另一个计算方面的帮助。我输入2和4,它应该计算2 * 2 + 3 * 3 + 4 * 4。如果我输入1和3它应该是1 * 1 + 2 * 2 + 3 * 3,我希望你理解!
#include <iostream>
#include <math.h>
using namespace std;
void sort(float & tal1, float & tal2);
int main() {
float x, y;
int sum, i, a, m, val;
cout << "Give to numbers: " << endl;
cout << "Type one number \n";
cin >> x;
cout << "Type another number \n";
cin >> y;
if (x > y) {
sort(x, y);
}
cout << x << " och " << y << endl;
cout << "Choose between a and m! " << endl;
cin >> val;
if (val == 'a') {
sum = 0;
for (int i = x; i <= y; i++)
sum += i;
cout << "Sum = " << sum << endl;
} else if (val == 'm') {
sum = 1;
for (int i = x + 1; i < y; i++) {
sum *= i;
cout << "Sum = " << sum << endl;
}
}
}
void sort(float & tal1, float & tal2) {
float temp = tal1;
tal1 = tal2;
tal2 = temp;
}
答案 0 :(得分:3)
for( int i = x ; i <= y ; i++ ){
sum +=i;
cout << "Sum = "<< sum <<endl;
}
这应该改为
for( int i = x ; i <= y ; i++ ){
sum +=(i*i);
cout << "Sum = "<< sum <<endl;
}
答案 1 :(得分:1)
我想你必须修改else分支来检查val是否是&#34; m&#34;
else if (val == 'm')
{
sum = 0;
for (int i = x; i <= y; i++)
{
sum += i*i;
cout << "Sum = "<<sum<<endl;
}
}