我是一年级的学生。有人能帮我做个任务吗?
简单calc C++
在第一行中,测试数n。在接下来的n行操作中,每个操作都包含操作类型(+ *)、要处理的k个数和k个数字。
输出结果
示例
输入
3
+ 3 3.1 5.2 -8.3
* 2 1 3.3
+ 1 3输出
0
3.3
3我的代码
int n, k;
char x;
cin >> n;
int tab[100];
for (int i = 0; i < n; i++)
{
cin >> x >> k;
for (int j = 0; j < k; j++)
{
cin >> tab[j];
if (x == '+')
{
tab[j] += tab[j + 1];
}
if (x == '*')
{
tab[j] *= tab[j + 1];
}
cout << tab[j];
}
}
return 0;
}发布于 2022-10-15 10:58:34
有几个问题。
float.
tab是int类型的,因此它只能存储整数,例如:1,2,3,4,5而不是1.3 2.5 3.3那样的浮点数,您应该考虑将tab更改为int类型。浮点累加器= 0;cin >> input_number;累加器+= input_number
我能给你的最好的建议是学会使用调试器,调试器是你的朋友,你应该用它来遍历你的代码,逐行地了解每一行对每个变量做了什么,并且读取每个变量的内容,我不能推荐一个学习使用调试器的特定来源,因为它取决于你的IDE,但是你也许应该在IDE X中检查一个关于使用调试器的视频,这对于学习如何使用IDE GUI是一个很好的开端。
发布于 2022-10-15 11:36:17
问题很多。只是一些:
tab的目的尚不清楚。您不需要存储操作数,您可以在一个值中积累一个结果。tab[j + 1];。如果您想要输出所有输入后的结果(如问题中所示),则需要在某个地方存储结果以供以后输出。H 212f 213F 213如果要使用清晰的变量名称来反映它们的目的,也许还需要一些评论,那么可能会产生更清晰的思想。如果您必须解释代码所做的事情(甚至对您自己),那么您经常会发现错误。一种很好的方法是首先编写注释,解释您需要编写的代码,而不是解释您编写的代码,并错误地假设代码是正确的。此外,你还需要摆脱“所有变量都在顶部”的习惯。
示例:
#include <iostream>
int main()
{
// Get number of calculations
int ncalc = 0 ;
std::cin >> ncalc ;
// Create array for results
double* result = new double[ncalc] ;
// For each calculation
for( int calc = 0; calc < ncalc; calc++ )
{
// Get the operator
char op = 0 ;
std::cin >> op ;
// Get the number of operands
int noperands = 0 ;
std::cin >> noperands ;
// Get initial operand in accumulator
double accumulator = 0 ;
std::cin >> accumulator ;
// For each remaining operand...
for( int i = 1; i < noperands; i++)
{
// Get the operand
double operand = 0 ;
std::cin >> operand ;
// Perform the operation
switch( op )
{
// For +, accumulate sum
case '+' : accumulator += operand ; break ;
// For * accumulate product
case '*' : accumulator *= operand ; break ;
}
}
// Store accumulated result
result[calc] = accumulator ;
}
// Output results
for( int calc = 0; calc < ncalc; calc++ )
{
std::cout << result[calc] << '\n' ;
}
delete[] result ;
return 0;
}https://stackoverflow.com/questions/74078559
复制相似问题