I need help understanding why code isn't working. I don't have a full understanding how to use argc and argv. I need to do addition, subtraction, multiplication, and division operations that can have multiple inputs. The addition is adding them all together, i was able to get that one. For the others, its taking the first input and either subtracting/dividing/multiplying by the rest. I'm using linux. To input the numbers, i would do (./.a.out 1 2 3 4) to input integers. Thank you
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main( int argc, const char * argv[])
{
float sum=0.0;
float sub=0.0;
float div=0.0;
float mult=0.0;
char ch;
printf("Pick a function \n");
scanf("%c", &ch);
int x,y;
switch(ch)
{
case ('A'):
{
x = argc -1;
for(y=0;y<x;y++)
{
sum = sum + atoi(argv[y+1]);
}
printf("The result of addition is %f\n",sum);
break;
}
case ('S'):
{
x = argc -1;
for(y=0;y<x;y++)
{
sub = sub - atoi(argv[y+1]);
}
printf("The result of subtraction is %f\n",sub);
break;
}
case ('M'):
{
x = argc -1;
for(y=0;y<x;y++)
{
mult = mult * atoi(argv[y+1]);
}
printf("The result of multiplication is %f\n",mult);
break;
}
case ('D'):
{
x = argc -1;
for(y=0;y<x;y++)
{
div = div / atoi(argv[y+1]);
}
printf("The result of division is %f\n",div);
break;
}
}
}
Here's the blueprint of what you need to fix:
#include <iostream>
// etc..
using namespace std;
float mult = 1.0;
float div = 1.0;
case ('M'):
{
x = argc - 1;
for (int y = 0; y < x; ++y)
{
mult = mult * atoi(argv[y+1]);
}
cout << "The result of multiplication is" << mult << endl;
break;
}
For subtraction and division, just have sub = atoi(argv[1]);
/ div = atoi(argv[1]);
outside of the loop, and set loop control variable to int y = 1
for both.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.