我只需将文件中的负数与内容相乘:12 7 -14 3 -8 10
。所以我需要-14乘以-8。
这是我的完整代码:
#include <stdio.h>
#include <math.h>
int main()
{
FILE *in, *out;
int x, negative, product;
in=fopen("C:\\Users\\emachines\\Desktop\\ind\\in.txt", "r");
if(in==NULL) //If file failed to open
{
printf ("Cannot open the file. Exiting...");
return -1;
}
printf("Numbers are:"); //Output integers
while(fscanf(in, "%d", &x)==1)
{
printf("%d ", x); //end of outputting integers
}
printf("\nNegative numbers are:"); //Output negative numbers
while(!feof(in))
{
fscanf(in, "%d", &negative);
while(negative<0)
{
printf("%d", negative); //end of outputting negative numbers
//multiply negative numbers
printf("mupltipying... Product - %d", product)
}
}
fclose(in);
return(0); //main returns int
}
那么如何只乘负数呢?如果我使用 x 变量输出所有数字,如何输出仅负数字? 对不起我的英语
最佳答案
在打印数字时检查是否小于 0,打印它并同时计算该数字的乘积。这是您的工作代码。
#include <stdio.h>
int main()
{
FILE *in, *out;
int x, negative, product=1;
in=fopen("a.txt", "r");
if(in==NULL) //If file failed to open
{
printf ("Cannot open the file. Exiting...");
return -1;
}
printf("Negative Numbers are:"); //Output integers
while(fscanf(in, "%d", &x)==1)
{
if(x<0){
product*=x;
printf("%d ", x); //end of outputting integers
}
}
printf("\n");
//multiply negative numbers
printf("mupltipying...\n Product=%d\n", product);
//printf("%d\n",product );
fclose(in);
return(0); //main returns int
}
关于c - 仅将负数相乘并仅从 C 中的文件中输出负整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26830964/