首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用特殊指令在C语言中计算5x+y表达式?

如何用特殊指令在C语言中计算5x+y表达式?
EN

Stack Overflow用户
提问于 2014-09-17 22:06:46
回答 1查看 116关注 0票数 0

我需要用C程序计算5x + y。我想通过实现calc5plusy函数来实现它,将x, y和指针作为参数。

如果检测到溢出,calc5plusy必须返回1。TI需要将x和y转换为64位类型(长为无符号int),执行计算,并确定结果是否大于无符号int的最大大小。如果检测到溢出,则需要返回一个非零值。如果未检测到溢出,请更新应答指针,并返回0。

我需要详细测试我的函数,以确保它正确地处理所有可能的32位输入,并提供正确的输出。

到目前为止,我要开始的工作如下所示,但由于我从未编写过C程序,所以我将它作为psedocode编写在任何有//标记的地方。请帮助我,因为我不知道在C和/或如果我这样做是正确的话,这将如何解释。这基本上是我的第一个C程序。您的帮助将不胜感激!

代码语言:javascript
复制
#include <stdio.h>

    // return_type name(arguments) {activities;}


    int main(void)
    {
        unsigned int overflow, answer;
        printf("an unsigned int is %lu bits!\n", 8 * sizeof (unsigned int));

        long long unsigned int x, y;

        overflow = calc5xplusy(/* Put your own arguments here */);

        // if x < 429
        // then 2^31-1-5*x *tells how large y may be so that there will be no overflow

        if (overflow) {
            printf("Overflow occurred!\n");
            return 1;
        } else {
            printf("Success: %u\n", answer);
            return 0;
        } 
    }

编辑:@Anton感谢您的建议!确实有帮助!以下是我在这个项目的最后结果:

代码语言:javascript
复制
#include <stdio.h>

unsigned int calc5xplusy(unsigned int x, unsigned int y, unsigned int *answer);

const unsigned int BIGGEST = 4294967295;

int main(void)
{
    unsigned int overflow, answer;

    printf("an unsigned int is %lu bits!\n", 8 * sizeof (unsigned int));

    overflow = calc5xplusy(5, 3, &answer);

    if (overflow) {
        printf("Overflow occurred!\n");
        return 1;
    } else {
        printf("Success: %u\n", answer);
        return 0;
    } 
}
unsigned int calc5xplusy(unsigned int x, unsigned int y, unsigned int *panswer)
{
    long long unsigned int value;
    value = (long long unsigned int)x * 5 + (long long unsigned int)y;
    if (value <= BIGGEST) {
        *panswer = (unsigned int)value;
        return 0;
    } else {
        return 1;
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-09-17 22:43:12

除了手动创建一组测试用例,您自己检查正确性,并在所有测试用例上运行您的函数,并将结果与所需的结果进行比较,没有其他方法可以测试您的函数。例如,可以这样做:

代码语言:javascript
复制
typedef struct Test {
    int x;
    int y;
    int overflow;
} Test;

Test tests[] = {
    {1, 2, 0},
    {1000000000, 1000000000, 1},
    // Add more tests here
};

numTests = sizeof(tests)/sizeof(tests[0]);
for (i = 0; i < numTests; ++i) {
    int res, overflow;
    overflow = calc5xplusy(tests[i].x, tests[i].y, &res);
    if (overflow != tests[i].overflow)
        printf("Test #%d failed\n", i);
}

在线演示

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25901109

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档