我想建立一个简单的计算程序来求和和总数。
当我尝试运行它时,总和和总的行为就像它们是零(没有给它们分配值),但我已经分配了它。谁能给我解释一下为什么会这样?如何解决这个问题?
#include<iostream>
using namespace std;
int main()
{
int a, b;
int sum;
cout << "Enter a number \n";
cin >> a;
cout << "Enter another number \n";
cin >> b;
sum = b - a;
cout << "Sum is: " << sum << endl;
int c= 60 * 60;
int d;
int total;
cout << "enter a number \n";
cin >> d;
total = c * d;
cout << "total is: " << total << endl;
int all;
all = sum / total;
cout << "all is: " << all << endl;
return 0;
}
有几件事。
不管什么原因,在你的代码中 sum = b - a
. 看来你的意思是 a + b
.
但是'all'的真正问题在于它是一个整数。对于整数,510(例如)是0,要解决这个问题,可以把你的代码改成:
float all;
all = float(sum) / total;
int a, b;
int sum;
cout << "Enter a number \n";
cin >> a;
cout << "Enter another number \n";
cin >> b;
sum = b - a;
cout << "Sum is: " << sum << endl;
int c= 60 * 60;
int d;
int total;
cout << "enter a number \n";
cin >> d;
total = c * d;
cout << "total is: " << total << endl;
// making all is double because (/) will give us
// an double value
double all;
all = (double )sum / total;
cout << "all is: " << all << endl;