c - 仅将负数相乘并仅从 C 中的文件中输出负整数

标签 c file while-loop output scanf

我只需将文件中的负数与内容相乘: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/

相关文章:

c# - 是否有可能知道哪个 .NET 代码创建了一个临时文件?

Android 本地存储文件在重启时被删除

java - 循环终止困惑

c - 通过 HTTP 接收数据 - 大小不一致

c - 为什么我得到错误的输出,我该如何解决这个问题?

mysql - 数据库来存储一棵巨大的树

php - 基于 <select> PHP/Mysql 更改输入值

c - 如何在这个函数中正确使用断言?

c - 信号处理程序 sa_sigaction 参数

java - 如何使用Java中类的成员方法从文件中读取数据?